![](/img/trans.png)
[英]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.