正则表达式代码在python中不起作用

2024-06-17 11:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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循环后的代码不起作用? 有人能帮我渡过难关吗?你知道吗


Tags: theto字符串代码importreforinput
1条回答
网友
1楼 · 发布于 2024-06-17 11:45:41

您应该首先查看^{}的文档,它的第三个参数是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.finditer和带有look aheadre.findall只返回匹配的文本。你知道吗

我想写这个函数是最好的方法。你知道吗


问得好。你知道吗

相关问题 更多 >