[英]Combine in an efficient way regex python
我動態創建一個正則表達式列表,即regex_list
。 列表中的每個正則表達式都肯定至少與應用的文本匹配。 列表中的某些正則表達式可能是相等的。
regex_list = []
for f in foo: # foo is a list of strings e.g. foo = ['foo1', 'foo2', 'foo1', ...]
# f is a valid expression to be used inside the regex
regex_list.append(f'[^.]*?{f}[^.]*\.')
regex = re.compile('|'.join(regex_list), flags=re.DOTALL)
result = re.findall(regex, text)
自從
regex_list
中的某些正則表達式可能等於regex_list
中的正則表達式與 OR 運算符組合在一起對於列表中存在另一個副本的正則表達式,僅捕獲文本中的第一個匹配項。
一種解決方法可能是使用 for 循環單獨應用每個正則表達式,但它非常慢。
有沒有一種結合正則表達式並使它們盡可能匹配的好方法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.