与PHP的preg_match相对应的Python

fun*_*guy 13 php python regex preg-match

我打算将我的一个刮刀移动到Python.我很舒服使用preg_match,并preg_match_all在PHP.我在Python中找不到合适的函数preg_match.有人可以帮我这样做吗?

例如,如果我想要得到的内容<a class="title"</a>,我用下面的函数在PHP中:

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

而在Python中,我无法找出类似的功能.

Ran*_*Rag 14

你正在寻找python的re模块.

看看re.findallre.search.

正如你所提到的,你正试图解析html的使用html parsers.python中有两个选项,如lxmlBeautifulSoup.

看看这个为什么你不应该用正则表达式解析html


Vas*_*riy 5

我认为你需要这样的东西:

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

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

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