开发者

Matching a line without either of two words

I was wondering how to match a line without either of two words?

For example, I would like to match a 开发者_运维百科line without neither Chapter nor Part. So neither of these two lines is a match:

("Chapter 2 The Economic Problem 31" "#74")

("Part 2 How Markets Work 51" "#94")

while this is a match

("Scatter Diagrams 21" "#64")

My python-style regex will be like (?<!(Chapter|Part)).*?\n. I know it is not right and will appreciate your help.


Try this:

^(?!.*(Chapter|Part)).*


@MRAB's solution will work, but here's another option:

(?m)^(?:(?!\b(?:Chapter|Part)\b).)*$

The . matches one character at a time, after the lookahead checks that it's not the first character of Chapter or Part. The word boundaries (\b) make sure it doesn't incorrectly match part of a longer word, like Partition.

The ^ and $ are start- and end anchors; they ensure that you match a whole line. $ is better than \n because it also matches the end of the last line, which won't necessarily have a linefeed at the end. The (?m) at the beginning modifies the meaning of the anchors; without that, they only match at the beginning and end of the whole input, not of individual lines.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜