Tim
Tim

Reputation: 99616

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.

Upvotes: 5

Views: 3546

Answers (2)

Alan Moore
Alan Moore

Reputation: 75272

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

Upvotes: 1

MRAB
MRAB

Reputation: 20664

Try this:

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

Upvotes: 10

Related Questions