为什么非捕获组(?:)似乎不工作?

时间:2022-01-09 12:16:22
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?

条件过期=后面应该有1-99之间的数字?

3 个解决方案

#1


11  

Your regex has spaces, remove them:

您的regex有空格,请删除它们:

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

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

而且regex 0[1-9]|[1-9][0-9]也不匹配0。

EDIT:

编辑:

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

根据您的评论,您希望在过期后允许1-99的数字=,以便您可以使用:

/^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.

因为您的示例在过期后为0 =它将不匹配。

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

还要注意,我已经添加了开始和结束锚。没有它们,regex可能匹配输入的任何有效子字符串。例如,它可以在input expire=999中匹配expire=99

#2


6  

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

如果您希望在正则表达式中使用空格,而不使用它们实际匹配的空格,则需要在正则表达式中使用x修饰符。例如/ foo /x匹配字符串“foo”,而/ foo /只匹配“foo”。

#3


2  

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

在第二个\s*和非捕获组的开始之间有一个空格。试试这个:

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

#1


11  

Your regex has spaces, remove them:

您的regex有空格,请删除它们:

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

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

而且regex 0[1-9]|[1-9][0-9]也不匹配0。

EDIT:

编辑:

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

根据您的评论,您希望在过期后允许1-99的数字=,以便您可以使用:

/^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.

因为您的示例在过期后为0 =它将不匹配。

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

还要注意,我已经添加了开始和结束锚。没有它们,regex可能匹配输入的任何有效子字符串。例如,它可以在input expire=999中匹配expire=99

#2


6  

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

如果您希望在正则表达式中使用空格,而不使用它们实际匹配的空格,则需要在正则表达式中使用x修饰符。例如/ foo /x匹配字符串“foo”,而/ foo /只匹配“foo”。

#3


2  

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

在第二个\s*和非捕获组的开始之间有一个空格。试试这个:

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