我想将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)
答案 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']]