简体   繁体   中英

Python regex: how to match strings that DO NOT contain an *exact* sentence?

I want to filter out messages from a log file that contain eg the sentence This is message 12345. Ignore.

If I would use grep, I could simple pass the sentence and use the -v switch, for example:

grep -v "This is message 12345\. Ignore\." data.log

The thing is, I have to do this in Python. Something like:

import re
with open("data.log") as f:
    data = f.read()
# This will select all lines that match the given sentence
re.findall(".*This is message 12345\. Ignore\..*$", data)

# HERE --> I would like to select lines that DO NOT match that sentence
# ???

I've tried to use (?...) and [^...] syntax (see here ), but I couldn't get it right.

Any ideas?

Use a negative lookahead assertion like this:

re.findall("(?!^.*This is message 12345\. Ignore\..*$).*", data)

and also enable the m modifier, so that ^ and $ match the start and the end of a row.

A simpler method to consider is to convert this to a positive matching problem:

  • Go through the file line by line
  • Perform a positive regex on the line, and if it matches, discard the line.

In general, negative matches with regexes get quite complicated. It is usually easier and more efficient to use a positive match to find the things you don't want, and then exclude those things with programming logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM