gpt4 book ai didi

python - 使用 RE 查找所有模式

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:01 24 4
gpt4 key购买 nike

我有这个字符串:

"(a) first, (b) second, (c) important"

我试图找到“(c) important”字符串之前的所有字符串,所以这是我的正则表达式:

"(?:\([a-z]\) ([a-z]+), )+\([a-z]\) important"

re.findall 只找到“second”字符串(没有“first”字符串)。
我尝试使用 re.finditer 和正则表达式模块(带有重叠标志),但它们都返回相同的结果。

这里应该做什么才能找到“重要”字符串之前的所有字符串?

备注-
输入字符串可以不同。例如:

"(a) aa, (b) cc, (c) dd, (d) oi, (e) important"  # should return ["aa", "cc", "dd", "oi"]   
"(a) aa, (b) asdf, (c) wer" # should return nothing

最佳答案

你可以使用

\([a-z]\)\s+([a-z]+)(?=(?:\s*,\s*\([a-z]\)\s+[a-z]+)*\s*,\s*\([a-z]\)\s+important)

参见 regex demo

详情

  • \([a-z]\) - 括号内的小写字母
  • \s+ - 1+ 个空格
  • ([a-z]+) - 第 1 组:括号内的一个或多个小写字母
  • (?=(?:\s*,\s*\([a-z]\)\s+[a-z]+)*\s*,\s*\([a-z]\)\s +important) - 与紧随其后的位置匹配的正面前瞻
    • (?:\s*,\s*\([a-z]\)\s+[a-z]+)* - 0 次或多次重复
      • \s*,\s* - 用 0+ 个空格括起来的逗号
      • \([a-z]\) - 括号中的字母
      • \s+ - 1+ 个空格
      • [a-z]+ - 1+ 个小写字母
    • \s*,\s* - 用 0+ 个空格括起来的逗号
    • \([a-z]\) - 括号内的小写字母
    • \s+ - 1+ 个空格
    • 重要 - 一个词。

Python demo :

import re
strs = ["(a) first, (b) second, (c) important", "(a) aa, (b) cc, (c) dd, (d) oi, (e) important", "(a) aa, (b) asdf, (c) wer" ]
r = re.compile(r'\([a-z]\)\s+([a-z]+)(?=(?:\s*,\s*\([a-z]\)\s+[a-z]+)*\s*,\s*\([a-z]\)\s+important)')
for s in strs:
print(r.findall(s))

输出:

['first', 'second']
['aa', 'cc', 'dd', 'oi']
[]

关于python - 使用 RE 查找所有模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com