Tree
Tree

Reputation: 10352

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

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?

Upvotes: 8

Views: 6743

Answers (3)

codaddict
codaddict

Reputation: 455272

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

Upvotes: 11

sepp2k
sepp2k

Reputation: 370357

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 ".

Upvotes: 6

Josh M.
Josh M.

Reputation: 27811

You have a space between the second \s* and the beginning of the non-capturing group. Try this instead:

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

Upvotes: 2

Related Questions