python - 仅在与其他匹配组不同时才匹配组

标签 python regex

我想用正则表达式匹配以 w 开头并以 d 结尾的每个子字符串。

例如对于输入 worldworld 它应该返回 ('worldworld', 'world', 'world')。 (注意:有两个 world 但它们是不同的,因为它们在字符串中的位置不同)

为此,我以这个程序结束 with following regex :

import re

s = '''worldworld'''

for g in re.finditer(r'(?=(w.*d))(?=(w.*?d))', s):
    print(g.start(1), g.end(1), g[1])
    print(g.start(2), g.end(2), g[2])
    print('-' * 40)

这打印:

0 10 worldworld
0 5 world
----------------------------------------
5 10 world
5 10 world
----------------------------------------

它找到所有子串,但有些也是重复的(注意组的开始和结束位置)。

之后我可以使用组的开始和结束位置过滤组,但我想知道是否可以通过更改我的正则表达式来完成,只返回唯一的组。

我可以将此正则表达式更改为仅匹配不同于其他组的组吗?如果是如何?我乐于接受有关如何解决此问题的建议。

最佳答案

我不相信这可以用一个正则表达式来完成。但是使用嵌套循环很简单:

import re
test = "wddddd"
# need to compile the tail regexp to get a version of
# `finditer` that allows specifying a start index
tailre = re.compile("(d)")
for wg in re.finditer("(w)", test):
    start = wg.start(1)
    for dg in tailre.finditer(test, wg.end(1)):
        end = dg.end(1)
        print(test[start : end], "at", (start, end))

显示:

wd at (0, 2)
wdd at (0, 3)
wddd at (0, 4)
wdddd at (0, 5)
wddddd at (0, 6)

test = "worldworldworld"

改为:

world at (0, 5)
worldworld at (0, 10)
worldworldworld at (0, 15)
world at (5, 10)
worldworld at (5, 15)
world at (10, 15)

关于python - 仅在与其他匹配组不同时才匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689418/

相关文章:

python - 在 XML 文件中查找标签

python - 如何使用 pandas.read_csv 将 CSV 文件中的数据插入到数据框中?

python - 在 Django 中将 CSS(和一般的静态文件)链接到 html

python - 在 Python 中读写内存

regex - Angular 2表单验证模式正则表达式错误

Python、Django mod_wsgi、virtualenv 错误 : ImportError: No module named os (paths are not correct)

javascript - 正则表达式 javascript 数字和字母

javascript - 首字母大写,其余字母小写,异常(exception)情况

r - 查找与字符串中的模式匹配的嵌套子字符串

c# - 匹配域名作为正则表达式