开发者

Stop at word in regex

I know that I can开发者_Python百科 do the following [^h] to get all matches accept the ones with a 'h'. How would I do this with an entire word, like ^(word)


If you want to match a string that is not identical to foo:

^(?!foo).*$

If you want to match a string that does not contain foo:

^(?!.*foo).*$

If you want to match a string that does not contain foo as a complete word:

^(?!.*\bfoo\b).*$

If you want to match a string until foo appears and stop the match before foo:

^(?:(?!foo).)*

These solutions do not handle newlines in the string, so you might have to set the corresponding regex options like RegexOptions.Singleline in .NET if that's a problem.

(?!foo) is a zero-width negative lookahead expression, meaning that it asserts that it is not possible ("negative") to match foo following the current position in the string ("look ahead"), while not consuming any characters in the match attempt ("zero-width").


There’s really no good way to do this with regular expressions. The nearest you can get is to use a negative lookahead that will find the regular expression only if it’s not followed by the string in the negative lookahead …:

foo(?!word)

Will only find foo not followed by word.

The same exists for looking behind (instead ahead):

(?<!word)foo

Will only find foo if it’s not preceded by word.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜