开发者

REGEX: Select everything NOT equal to a certain string

开发者 https://www.devze.com 2023-01-28 18:55 出处:网络
This should be straightforward. I need a re开发者_C百科gular expression that selects everything that does not specifically contain a certain word.

This should be straightforward. I need a re开发者_C百科gular expression that selects everything that does not specifically contain a certain word.

So if I have this sentence: "There is a word in the middle of this sentence." And the regular expression gets everything but "middle", I should select everything in that sentence but "middle".

Is there any easy way to do this?

Thanks.


It is not possible for a single regex match operation to be discontinuous.

You could use two capturing groups:

(.*)middle(.*)

Then concatenate the contents of capturing groups 1 and 2 after the match.

You may wish to enable the "dot also matches newline" option in your parser.
See for example Java's DOTALL, .NET's Singleline, Perl's s, etc.


Positive lookaround is the way to go:

/^(.+)(?=middle)/ -- gets everything before middle, not including middle

and

/(?!middle)(.+)$/ -- gets everything after middle, not including middle

Then you just merge the results of both

0

精彩评论

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

关注公众号