Regex explanation..

5 views
Skip to first unread message

Jerome Jean Verleyen

unread,
Nov 21, 2024, 2:45:37 PM11/21/24
to help-cfengine
Dear all.

I'm using the book Learning CFEngine 3, to trying to configure some computer here.
I wrote the code to detect the specific ethernet card that have some specific ipv4 format. In my case, "172.16.1.*".

What i notice is that i could not escape the point caracter ".". For example, this code don't detect anything:

 bundle agent my_test
{

  vars:
      "ipregex" string => "172\.16\.1\.*";

  classes:
      "found" expression => regcmp("$(ipregex)","172.16.1.10");
     
  reports:
    found::
      "Found the ip ";

    !found::
      " Don't found the ip";
     
}

bundle agent __main__
{
      methods: "my_test";
}

Running this promise get me back:

R:  Don't found the  ip

But if i change the regex to "172.16.1.*" :

R: Found the  ip

Even if i put a wrong ip like this:

"found" expression => regcmp("$(ipregex)","172a16.1.10");

R: Found the  ip

I've read about PCRE Regex and "." is considered as any caracter.. So, why i could not "escape" the point "\." in my rule?

Hope that's someone could explain this!
Regards

Nick Anderson

unread,
Nov 21, 2024, 3:39:38 PM11/21/24
to help-cfengine

Your regex seems incorrect to me. You escaped the dot, but then you used * to repeat zero or more times. Try an extra dot in your regex, un-escaped?

Better yet, don't use regular expressions to match on IP addresses if you can avoid it. Maybe iprange(), or isipinsubnet() would be a good fit for you.

Here I hacked at your example:

bundle agent my_test
{

  vars:
      "ipregex" string => "172\.16\.1\.*"
;
      "ipregex2" string => "172\.16\.1\..*";

  
classes:
      "found" expression => regcmp("$(ipregex)","172.16.1.10")
;
      "found2" expression => regcmp("$(ipregex2)","172.16.1.10");

  
reports:
    found::
      "Found the ip "
;

    found2::
      "Found the ip2 ";

    
!found::
      " Don't found the ip"
;

    !found2::
      " Don't found the ip2";


}

bundle agent __main__
{
      methods: "my_test";
}

R: Found the ip2
R:  Don't found the ip

Jerome Verleyen

unread,
Nov 22, 2024, 10:19:35 AM11/22/24
to help-c...@googlegroups.com
-

Dear Nick.

Thank's for your answer. I was wrong in this Regex... I forgot the ultimate point caracter that is important in a anchored regex!

And i will use the iprange, that's help me a lot in other stuff with cfengine..

Regards!



-- Jérôme 
Pourquoi les établissements ouverts 24 heures sur 24 ont-ils des serrures ? 
	(Anonyme)
Reply all
Reply to author
Forward
0 new messages