对应于Python中PHP的preg_match

2024-04-19 13:51:30 发布

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

我打算把我的一个刮刀移到Python上。我很乐意在PHP中使用preg_matchpreg_match_all。我在Python中找不到类似于preg_match的合适函数。有人能帮我吗?

例如,如果我想获取<a class="title"</a>之间的内容,我在PHP中使用以下函数:

preg_match_all('/a class="title"(.*?)<\/a>/si',$input,$output);

而在Python中,我无法找到类似的函数。


Tags: 函数内容inputoutputtitlematchallclass
3条回答

你在找Python的re module

看看re.findallre.search

正如您所提到的,您正在尝试解析html,为此使用html parsers。python中有两个选项可用,比如lxmlBeautifulSoup

看看这个Why you should not parse html with regex

我想你需要这样的东西:

output = re.search('a class="title"(.*?)<\/a>', input, flags=re.IGNORECASE)
    if output is not None:
        output = output.group(0)
        print(output)

你可以加上?s) 在regex开始时启用多行模式:

output = re.search('(?s)a class="title"(.*?)<\/a>', input, flags=re.IGNORECASE)
    if output is not None:
        output = output.group(0)
        print(output)

相关问题 更多 >