【问题标题】:how to find more than one match with a regular expression? [duplicate]如何使用正则表达式找到多个匹配项? [复制]
【发布时间】:2020-02-08 02:04:06
【问题描述】:

我有一个这样的字符串:

to_search = "example <a>first</a> asdqwe <a>second</a>"

我想在这样的之间找到两种解决方案:

list = ["first","second"]

我知道在寻找一种解决方案时我应该使用以下代码:

import re

if to_search.find("<a>") > -1:
    result = re.search('<a>(.*?)</a>', to_search)
    s = result.group(1)
    print(s)

但这只会打印:

first

我尝试了 result.group(2) 和 result.group(0) 但我得到了相同的解决方案


如何列出所有解决方案?

【问题讨论】:

标签: python regex


【解决方案1】:

最好使用 HTML 解析器而不是正则表达式,但将 re.search 更改为 re.findall

【讨论】:

    【解决方案2】:
    to_search = "example <a>first</a> asdqwe <a>second</a>"
    for match in re.finditer("<a>(.*?)</a>", to_search):
        captured_group = match.group(1)
        # do something with captured group
    

    【讨论】:

      【解决方案3】:

      只需使用:

      import re
      to_search = "example <a>first</a> asdqwe <a>second</a>"
      matches = re.findall(r'<a>(.*?)</a>', to_search)
      print(matches)
      

      输出

      ['first', 'second']
      

      【讨论】:

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