python在2 delimi之间查找多个匹配项

2024-10-03 19:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用regex查找两个分隔符之间的多个匹配项。 不幸的是我不知道怎么做。 两个分隔符是“and”:

import re
string = "'lightOff' 'lightOn':,'lightOff' 'ovenOff' 'ovenOn': None 'radioOn': 'radioOff'"
print string
print 'newString', re.findall("^'(.*?)':", string)

我只得到第一场比赛

^{pr2}$

我想要的是得到'and'之间的3个子字符串:

'lightOn'
'ovenOn'
'radioOn'

Tags: andimportrenonestringregexprint分隔符
3条回答

下面的正则表达式也可以工作

'[^']*'(?=:)

python代码是

^{pr2}$

如果不想在最终结果中包含',那么使用lookahead和lookbehind。在

>>> m = re.findall(r"(?<=')[^']*(?=':)", string)
>>> for i in m:
...     print i
... 
lightOn
ovenOn
radioOn

不要使用锚。^和{}是regex模式中的锚定。另外,当您在两个'之间匹配时,它将返回字符串'word1' 'word2':作为输出,而不仅仅是'word2':。尝试匹配两个'之间的所有内容,这不是字符'本身。在

re.findall("'([^']+)':", string)

会有用的。在

What i want is to get the 3 substrings between ' and '

只需尝试不使用Lookaround和{a2}捕获组

(?<=')[^']+(?=':)

这是demo

关于^{}关于性能回溯的一篇值得阅读的文章

However, a lazy quantifier has a cost: at each step inside the braces, the engine tries the lazy option first (match no character), then tries to match the next token (the closing brace), then has to backtrack. Therefore, the lazy quantifier causes backtracking at each step.

enter image description here

相关问题 更多 >