【问题标题】:How to find overlapping patterns in a regex? [duplicate]如何在正则表达式中找到重叠模式? [复制]
【发布时间】:2017-07-05 10:52:04
【问题描述】:

假设我有一个像 123456789 这样的字符串。有没有办法像这样从给定的字符串中找到所有可能的现有模式

123423453456456756786789 使用regex

我这样做了,但找不到解决方案:

import re
regex = r"[1-9]{4}"
test_string = "123456789"
print(re.findall(regex, test_str))

这个输出:

['1234', '5678']

任何帮助对我来说都意义重大,谢谢

【问题讨论】:

    标签: python regex python-2.7 python-3.x


    【解决方案1】:

    你可以试试这个正则表达式:

    \d(?=(\d{3}))
    

    Regex Demo

    示例源 (Run here)

    import re
    regex = r"\d(?=(\d{3}))"
    test_str = "123456789"
    matches = re.finditer(regex, test_str)
    
    for match in matches:
     print(match.group()+match.group(1));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多