开发者

What does "?:" do in regex?

I wanted to match anything but a string using regex. I did some Googling and found this:开发者_如何学编程 ^(?:(?!test).)* What do ?: and ?! do? Thanks.


(?:) is non-capturing. That means that a match occurs as usual, but the parentheses are only for grouping (in this case to attach a * operator to the entire thing); the matched value cannot be pulled out later with $1 or \1.

(?!) is a negative lookahead assertion. That means that it matches if the string in the parentheses does not exist there.

See http://docs.python.org/library/re.html for some more operators. While regex varies in different languages, they're fairly similar.


yes ... and (?!) is a "zero-width negative look-ahead assertion." according to "perldoc perlre".

It means don't match the thing in the parens. Tje example from the docs is:

For example "/foo(?!bar)/" matches any occurrence of "foo" that isn’t followed by "bar".

So in this example foobar wouldn't match, but fooxbar would, as would foo and foofoo and so on.

Oh yes, so the example you gave should match anything not containing "test". I think it's clearer to match /test/ and negate outside the regex evaluation, as in "grep -v test"


The ?! indicates a negative look ahead. The expression containing the negative look ahead will only return a match if the expression inside the negative look ahead fails to match. This means that "(?!test)." will only return a match if "test" is not matched.

The outer grouping "(?:(?!test).)" is called a passive grouping and is functionally equivalent to "((?!test).)". The difference is that with a passive grouping, no back references are created, so it's more efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜