Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the non-capturing group (?:) seem to not be working?

Tags:

string

regex

perl

my $str='expire=0';

if ($str =~/expire\s*=\s* (?: 0[1-9]|[1-9][0-9])/){
    print " found it ";
}

its not working

Condition expire= should be followed by a number between 1-99?

like image 319
Tree Avatar asked Mar 03 '11 12:03

Tree


2 Answers

If you want to use spaces in your regex without them actually matching spaces, you need to use the x modifier on your regex. I.e. / foo /x matches the string "foo", while / foo / only matches " foo ".

like image 31
sepp2k Avatar answered Nov 15 '22 21:11

sepp2k


Your regex has spaces, remove them:

/expire\s*=\s* (?: 0[1-9]|[1-9][0-9])/
              ^   ^ 

Also the regex 0[1-9]|[1-9][0-9] does not match 0.

EDIT:

Based on your comments, you want to allow a number from 1-99 after expire= so you can use:

/^expire\s*=\s*(?:[1-9]|[1-9][0-9])$/

or a shorter version:

/^expire\s*=\s*(?:[1-9][0-9]?)$/

Since your example has 0 after expire= it'll not be matched.

Also note that I've added the start and end anchors. Without them the regex may match any valid sub-string of the input. Example it can match expire=99 in the input expire=999

like image 117
codaddict Avatar answered Nov 15 '22 21:11

codaddict