【问题标题】:How can I store multiple strings into a list from regex?如何将多个字符串存储到正则表达式的列表中?
【发布时间】:2012-05-11 17:47:52
【问题描述】:

这是我的字符串:

<span class="word">blue</span><span class="word">red</span><span class="word">yellow</span><span class="word">orange</span>

通常我会使用它来将一个结果放入变量中:

result = re.search('(<span class="word">)(.*)(</span>)', string)
color = result.group(2)

但现在我想从我的字符串中获取 每个 结果并将每个结果存储到一个列表中。我该怎么做呢?

【问题讨论】:

  • 你应该使用 BeautifulSoup 来达到这个目的。

标签: python arrays list


【解决方案1】:

re.findall。对于较大的字符串,我推荐re.finditer

【讨论】:

    【解决方案2】:

    使用 findall 代替搜索

    findall() 查找 RE 匹配的所有子字符串,并将它们作为列表返回。

    finditer() 查找 RE 匹配的所有子字符串,并将它们作为迭代器返回。

    http://docs.python.org/howto/regex.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2011-02-17
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多