Skip to main content
 首页 » 编程设计

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

2024年08月25日26yyy_WW

我想将 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) 

请您参考如下方法:

根据子串或进行拆分即可

re.split(r' or ', s) 

或

re.split(r'\s+or\s+', s)