python - 正则表达式查找器 : search twice on the same symbols

标签 python regex

我需要在文本中找到匹配项并获取其位置。例如,我要在文本中找到“hello hello”。当文本是“你好 Hello World 你好你好”时,没关系,我得到了位置 0-11 和 18-29。但是当文本是“hello hello hello world”时,我只得到一个位置——0-11。但我必须找到这两个(0-11 和 6-17)。我是说,我明白了

  1. 你好你好 Hello World

但必须得到

  1. 你好你好 Hello World

  2. 你好你好你好世界

在另一种情况下,我必须找到复杂的模式:“hello 1,2 beautiful 2,4 world”——这意味着“hello”和“beautiful”这两个词之间可能是一个或两个词,“美丽”和“世界”2、3 或 4 个词。我必须找到所有的组合。

这是模式:re.compile(u'(^|[\[\]\/\\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@])(hello)(([\[\]\/\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@%]+[a-zA-Zа-яА-Я$]+(-[a-zA-Zа-яА-Я$]+)*){1,2}[\[\]\/\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@%]*)(beautiful)(([\[\]\/\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@%]+[a-zA-Zа-яА-Я$]+(-[a-zA-Zа-яА-Я$]+)*){2,4}[\[\]\/\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@%]*)(world)($|[\[\]\/\\\^\$\.\|\?\*\+\(\)\{\} !<>:;,#@])')

文字是“你好非常美丽美丽非常大的世界世界”。我只能得到一个组合,但需要得到 4 个:

  1. 你好非常美丽美丽非常大的世界世界

  2. 你好很漂亮很漂亮很大世界世界

  3. 你好非常美丽美丽非常大的世界世界

  4. 你好很漂亮很漂亮很大的世界世界

当火柴相互交叉时,如何得到火柴的所有组合?

标志 re.DOTALL 没有帮助。

import re

patterns = [
    u'(hello)(( [a-z]+ *){1,2})(beautiful)(( [a-z]+ *){2,4})(world)',
    u'hello hello'
]
text = u'hello hello hello world hello very beautiful beautiful very big world world'
for p in patterns:
    print p
    c = re.compile(p, flags=re.I+re.U)
    for m in c.finditer(text):
        print m.start(), m.end()

结果是

>>> (hello)(( [a-z]+ *){1,2})(beautiful)(( [a-z]+ *){2,4})(world)
>>> 24 69
(need 24 69 and 24 69 and 24 75 and 24 75 - because there are two positions of the word "beautiful")
>>> hello hello
>>> 0 11
(need 0 11 and 6 17)

模式的真实例子是:

u"выйдите на улицы", u"избавить.* от", u"смотрите смотрите", u"смеят.*"

还有距离:

имени 0,3 ленина

целых 0,5 лет.*

целых 0,5 лет.* 0,1 назад

UPD

变体 u'(?=(hello hello))有助于单词之间没有距离的模式。但是我如何在有距离的模式中使用它,例如 (hello) (?:[a-zA-Zа-яА-Я]+ ){1,2}(beautiful) (?:[a-zA-Zа-яА-Я]+ ){2,4}(world)

最佳答案

你的问题仍然不清楚你想做什么,但我会试一试:

使用正则表达式查找不消耗的重复项:

([a-zA-Zа-яА-Я]+)(?= (\1))

使用正则表达式查找 hello beautifulworld 之间有特定数量的单词:

(hello) (?:[a-zA-Zа-яА-Я]+ ){1,2}(beautiful) (?:[a-zA-Zа-яА-Я]+ ){2,4}(world)

最终更新

你想做的事情在正则表达式中一次运行并不容易完全完成。

更简单的方法是循环并执行不同的正则表达式:

for i in range(1,3):
    for j in range(2,5):
        regStr='(hello) (?:\w+ ){' + str(i) + '}(beautiful) (?:\w+ ){' + str(j) +'}(world)'

然后使用

再次检查重复项
([a-zA-Zа-яА-Я]+)(?= (\1))

关于python - 正则表达式查找器 : search twice on the same symbols,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38916664/

相关文章:

python - 两个相同比例的y轴

带有正则表达式的 Python difflib

Notepad++ 中的正则表达式 - 在 Notepad++ 中删除 “\n”字符后的换行符 “$”

c# - RegEx替换C#中字符串中的特定字母

python - 替换所有出现的连续重复值对

python - 针对 lexsort : Permutation for sorting each column independently when considering yet another vector 的二维数组广播一维数组

python - 如何以编程方式链接 slack 消息

Python:从字符串中提取多个 float

Python LXML 从 Steam Bundle 页面获取数据 - 列出索引错误

php - 如何在mysql数据库中插入新字段