首页 > 解决方案 > Python查找所有正则表达式字符串值

问题描述

我想查找所有链接标题(使用bs4进行抓取)包含字符串:“news”或“reporting”(标题包含两个单词应该是结果)

我试过:

search = re.compile(r"news")
search1 = re.compile(r"reporting")
for text in box.find_all("p",text= search or search1):
   #dosth

search = re.compile("news.+reporting")
for text in box.find_all("p",text= search or search1):
   #dosth

但这两个代码只返回匹配“新闻”而不匹配“报道”,所以想知道如何做到这一点?提前致谢!

标签: python

解决方案


你应该看看这样的东西

search = re.compile(r"reporting|news")
for text in box.find_all("p",text=search):
   #dosth

注意这个|字符,它or在正则表达式中起作用。可|用于or任意正则表达式和表达式组。查看文档以获取更多信息。


推荐阅读