[英]How to do exact match in a paragraph of by using the list of strings in python
[英]Python regex: how to match strings that DO NOT contain an *exact* sentence?
我想从日志文件中过滤出包含例如句子This is message 12345. Ignore.
如果我使用grep,我可以简单地传递句子并使用-v
开关,例如:
grep -v "This is message 12345\. Ignore\." data.log
问题是,我必须在Python中执行此操作。 就像是:
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
# ???
我试过使用(?...)
和[^...]
语法(见这里 ),但我无法正确使用它。
有任何想法吗?
使用这样的负向前瞻断言 :
re.findall("(?!^.*This is message 12345\. Ignore\..*$).*", data)
并启用m
修饰符,以便^
和$
匹配行的开头和结尾。
一个更简单的方法是将其转换为正匹配问题:
通常,与正则表达式的否定匹配变得相当复杂。 使用肯定匹配来查找不需要的内容通常更容易,更有效,然后使用编程逻辑排除这些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.