Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl pattern match not working as expected

Tags:

regex

perl

I'm trying to match values, which may be comma separated, using a regex. Basically, I want to return true if any value in the string does NOT have 3g or 3k starting in the 3rd position.

My test code is as follows:

my @a = ('in3g123456,dh3k123456,dhec110101','dhec110101,dhec123456','in3g123456,dh3k123456', 'c3kasdf', 'usdfusdufs3gsdf' );

foreach (@a) {
  print $_;
  say $_ =~ /(?:^|,)\w{2}[^(?:3G|3K)]/i ? " true" : " false";
}

This returns

in3g123456,dh3k123456,dhec110101 true
dhec110101,dhec123456 true
in3g123456,dh3k123456 false
c3kasdf false   <- whaaaaaaaat?
usdfusdufs3gsdf true

I don't understand why the 4th one is not true. Any help would be appreciated.

like image 748
Jim Avatar asked May 07 '26 05:05

Jim


1 Answers

[^(?:3G|3K)] reads as "any character but (, ?, etc."

                      failed
                      v
        c3            kasdf
/(?:^|,)\w{2}[^(?:3G|3K)]/i

Use this:

/(?:^|,)\w{2}(?!3G|3K)/i

Demo: https://regex101.com/r/P2XsgN/1.

like image 165
Kirill Bulygin Avatar answered May 08 '26 23:05

Kirill Bulygin