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

标签 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)

最佳答案

只需根据子字符串进行拆分

re.split(r' or ', s)

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

关于Python 使用正则表达式对相似模式进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429399/

相关文章:

python - Django 登录无法正常工作

c# - 多个字符串在正则表达式中具有特殊字符

regex - 使用 maven-replacer-plugin 选择性替换正则表达式

python - 更改youtube/dailymotion/vimeo嵌入大小

C++:使用 isdigit 检查字符串字符是否为数字。 .

python - 我想从 dict 创建一个 df,其中 1 列是 dict.keys,另一列是 dict 值

python - 如何从 python 调用 MiKTeX 生成 pdf?

java - 根据大写和数字拆分字符串

Python - 读取和删除文件的顶行而不将其加载到内存中

mysql - 如何在 mysql 列中查找和替换单词?