【问题标题】:Regex code not working in python正则表达式代码在 python 中不起作用
【发布时间】:2017-02-17 16:33:21
【问题描述】:
import re
st=input()  #The input string
ss=input()  #The substring to be searched
lss=len(ss)
lst=len(st)
x=lst-lss
for i in range(x):
    r=re.search(r'(%s)'%ss,st,i)
    if r:
        print(r.start(),r.end())

上面的代码是对任务的响应。任务是:

给出一个字符串 S。

我需要在 S 中找到字符串 k 的开始和结束的索引。

如果输入是:

aaadaa
aa

输出应该是:

(0, 1)  
(1, 2)
(4, 5) 

我知道我写的代码是错误的,因为我没有得到想要的输出。我在 for 循环之后再次遍历了一行。我无法说服自己这是错误的。我只想知道为什么 for 循环之后的代码不起作用? 有人可以帮我解决吗?

【问题讨论】:

  • 我认为你不应该像那样将i 传递给search。搜索的第三个参数是flags,而不是“开始搜索的索引”,如果这是你想要做的。
  • 你甚至不需要正则表达式(这是一种矫枉过正)。使用标准string.find()

标签: python regex python-3.4


【解决方案1】:

你应该先看re.search()的文档,它的第三个参数是flag


在你的情况下,你正在寻找重叠结果,我意识到没有直接的解决方案,所以我写了一个递归

import re
string = input()  # The input string
pattern = input()  # The substring to be searched

def match(pattern, string, startIdx=0):
    if startIdx <= len(string) - len(pattern):
        res = re.search(pattern, string[startIdx:])
        if res is not None:
            print(res.start() + startIdx, res.end() + startIdx - 1)
            return match(pattern, string, startIdx + res.start() + 1)


match(pattern, string)

谁的输出是

0 1
1 2
4 5

它应该可以按照您的预期完成工作。


我检查了预先存在的解决方案,它们不符合您的要求:

  • re.finditer 只能进行非重叠搜索。
  • re.findall 进行重叠搜索,但未能检索到索引。
  • re.finditerre.findalllook ahead 仅返回匹配的文本。

我想编写这个自己的函数是最好的方法。


不过,这是个好问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多