【问题标题】:Regex search and grep everything between the second occurrence of first keyword and second keyword in a string - Python正则表达式搜索和 grep 字符串中第二次出现的第一个关键字和第二个关键字之间的所有内容 - Python
【发布时间】:2023-03-05 11:01:01
【问题描述】:
example_string = 'Hello A Bye, Hello B Ciao."

通缉:"B"

我要使用的:re.search()

正常方法:

res = re.search(r'Hello(.*?)Ciao', example_string)

但这种方法会输出:"A Bye, Hello B"

有没有办法告诉程序第二次出现第一个关键字。所以在这种情况下,它会在字符串中搜索单词“Hello”的第二次出现,并将其作为res 中的第一个关键字。

这样它就会简单地输出:"B"

有人知道如何解决这个问题吗?

谢谢。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    我们可以在这里使用re.findall查找所有匹配项,然后访问第二个匹配项:

    example_string = "Hello A Bye, Hello B Ciao."
    matches = re.findall(r'\bHello (\w+)', example_string)
    print(matches[1])  # B
    

    【讨论】:

      【解决方案2】:

      使用re.findall 可以工作,findall() 可能是re 模块中最强大的函数。上面我们使用 re.search() 来查找模式的第一个匹配项。 findall() 找到 所有 个匹配项并将它们作为字符串列表返回,每个字符串代表一个匹配项。

      示例:-

      text = "He was carefully disguised but captured quickly by police."
      >>> re.findall(r"\w+ly", text)
      >>> ['carefully', 'quickly']
      
      

      【讨论】:

        猜你喜欢
        • 2018-03-13
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多