Python中PHP的preg_match对应函数

16 投票
3 回答
26712 浏览
提问于 2025-04-17 11:56

我打算把我的一个爬虫程序转到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中,我找不到一个类似的函数。

3 个回答

2

你可能会对阅读 Python 正则表达式操作 感兴趣。

5

我觉得你需要这样的东西:

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

你可以在正则表达式的开头加上 (?s) 来启用多行模式:

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

你可以看看Python的re模块

可以关注一下re.findallre.search这两个功能。

而且你提到你想解析HTML,建议使用html解析器来做这个。Python里有几个选择,比如lxml或者BeautifulSoup

可以看看这个为什么不应该用正则表达式解析HTML的讨论。

撰写回答