簡體   English   中英

正則表達式匹配引號之間字符串的首次出現,但排除某些單詞?

[英]Regex to match the first occurrence of a string between quotes, but exclude certain words?

我有一個正則表達式,可以捕獲文本文件中引號內的所有字符,但我想:

  • 僅匹配此模式的第一次出現
  • 從此模式匹配中排除某些單詞

這是我到目前為止的內容:

((?:\\.|[^"\\])*)

匹配引號內的所有文本,如下所示:

這是上面印有文字的文字嗎?

但是,我希望模式僅匹配第一次出現的內容,因此我認為在某個時候需要{1}。

然后,我想排除某些單詞,並且我有:

^(?!.*word1|word2|word3)

但是我對正則表達式還不夠熟悉,無法將它們放在一起。

我認為您可以使用此正則表達式來匹配字符串中首次出現的雙引號,該雙引號不包含列表中的單詞:

^.*?(?!"[^"]*?\b(?:word1|word2|word3)\b[^"]*?")"([^"]+?)"(?=(?:(?:[^"]*"[^"]*){2})*[^"]*$)

觀看演示

樣例代碼

import re
p = re.compile(ur'^.*?(?!"[^"]*?\b(?:word1|word2|word3)\b[^"]*?")"([^"]+?)"(?=(?:(?:[^"]*"[^"]*){2})*[^"]*$)')
test_str = u"\"word that is not matched word1\" \"word2 word1 word3\" \"this is some text word4 with the word printed in it?\""
print re.search(p, test_str).group(1)

輸出:

this is some text word4 with the word printed in it? 

至於可維護性,可以從任何來源提取被排除的單詞,並且可以動態構建正則表達式。

是否必須使用單個正則表達式一次即可解決所有這些要求? 如果您只使用一個簡單的正則表達式來查找帶引號的字符串,然后根據排除的單詞黑名單過濾所有匹配項,最后選擇剩下的第一個,則代碼的可維護性將大大提高。

excluded = ('excluded', 'forbidden')
text = 'So, "this string contains an excluded word". "This second string is thus the one we want to find!" another qu"oted st"ring ... and another "quoted string with a forbidden word"'

import re
quoted_strings = re.findall('".*?"', text)
allowed_quoted_strings = [q for q in quoted_strings if any(e in q for e in excluded)]
wanted_string = allowed_quoted_strings[0]

或者,如果您喜歡用一個巨大的單表達

import re
wanted_string = [q for q in re.findall('".*?"', 'So, "this string contains an excluded word". "This second string is thus the one we want to find!" another qu"oted st"ring ... and another "quoted string with a forbidden word"') if any(e in q for e in ('excluded', 'forbidden'))][0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM