[英]Find all occurrences of regex pattern, but ignore occurrences that contain another pattern
[英]find all occurrences between 2 values in non default pattern
我在 python 中遇到了正則表達式搜索的問題
所以我有:
testVariable = re.findall(r'functest(.*?)1', 'functest exampleOne [2] functest exampleTwo [1] functest exampleOne throw [2] functest exampleThree [1]')
當前Output是:
[' exampleOne [2] functest exampleTwo [', ' exampleOne throw [2] functest exampleThree [']
但我想要的是根據需要找到 'functest' & 1' <or 2, or 3> 之間的所有出現,所以 output 應該是這樣的:
['exampleTwo [, exampleThree [']
這是因為以上兩者都在我需要的 functest & 1 之間。 有人知道嗎?
如果匹配第一次出現的 1 或 3 之間不能有任何數字:
\bfunctest\b\s*(\D*)[13]\b
模式匹配:
\bfunctest\b\s*
匹配單詞 functest 后跟可選的空白字符(\D*)
捕獲組 1 中的可選非數字[13]
匹配 1 或 3\b
單詞邊界請參閱正則表達式演示。
或者您可以在使用否定字符 class 匹配數字之前排除匹配方括號:
\bfunctest\b\s*([^][]*\[)[13]]
請參閱另一個正則表達式演示。
例子
import re
pattern = r"\bfunctest\b\s*([^][]*\[)239]"
s = "functest exampleOne [2] functest exampleTwo [239] functest exampleOne throw [2] functest exampleThree [1] functest exampleFour [2] functest exampleFive [239]"
print(re.findall(pattern, s))
Output
['exampleTwo [', 'exampleFive [']
通過使用以下找到了一種方法。 它仍然包括 functest,但至少可以完成工作
testVariable = re.findall(r'functest(?:(?.functest)?)*,239', 'functest exampleOne [2] functest exampleTwo [239] functest exampleOne throw [2] functest exampleThree [1] functest exampleFour [2] ] functest exampleFive [239]')
Output: ['functest exampleTwo [239', 'functest exampleFive [239']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.