Python使用正则表达式对类似的模式进行分组

时间:2015-10-30 05:42:41

标签: python regex string

我想将or与我获得的字符串匹配,并根据or出现的时间对结果进行分组。

我的输入将是:

a or b*~c or 27*y or 5*~b

所以我的输出应该是:

a, b*~c, 27*y, 5*~b

如果只有3 or,我的代码可以正常工作,但否则会返回[]

我是python的新手,我不确切地知道如何将模式赋予编译函数。

import re
input = raw_input(" ")

ans = re.compile(r'(.*) or (.*) or (.*) or (.*)')
print re.findall(ans, input)

2 个答案:

答案 0 :(得分:2)

只需根据子字符串<script type="text/javascript" src="path-to-MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

进行拆分
or

re.split(r' or ', s)

答案 1 :(得分:1)

您可以在不使用split的情况下执行简单的re

input = raw_input()
ans = input.split("or")

ans = input.split(" or ")

如果您想使用findall,可以使用

x="a or b*~c or 27*y or 5*~b"
print re.findall(r"(?:^|(?<=\bor\b))\s*(.*?)\s*(?=\bor\b|$)",x)

*or使用

x="a or b*~c or 27*y or 5*~b"
print [i.split("*") for i in x.split(" or ")]

输出:[['a'], ['b', '~c'], ['27', 'y'], ['5', '~b']]