我在使用 Python 正则表达式时遇到了一个小问题。
假设这是输入:
(zyx)bc
我想要实现的是获取括号之间的任何内容作为单个匹配项,以及获取括号之外的任何字符作为单独的匹配项。期望的结果将是:
['zyx','b','c']
应保持匹配顺序。
我试过用 Python 3.3 获得它,但似乎无法找出正确的正则表达式。到目前为止,我有:
matches = findall(r'\((.*?)\)|\w', '(zyx)bc')
print(matches)
产生以下结果:
['zyx','','']
知道我做错了什么吗?
最佳答案
来自re.findall
的文档:
If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.
当您的正则表达式与字符串匹配三次时,(.*?)
组在后两次匹配中为空。如果你想要另一半正则表达式的输出,你可以添加第二组:
>>> re.findall(r'\((.*?)\)|(\w)', '(zyx)bc')
[('zyx', ''), ('', 'b'), ('', 'c')]
或者,您可以删除所有组以再次获得一个简单的字符串列表:
>>> re.findall(r'\(.*?\)|\w', '(zyx)bc')
['(zyx)', 'b', 'c']
不过您需要手动删除括号。
关于python - 使用交替运算符匹配多个正则表达式模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14182339/