在 findall 语句中使用 " 发出

Issue with " in a findall statement

我 运行 遇到了在 python 搜索 html 源代码的正则表达式 findall 语句中使用 " 的问题。

我正在搜索一些 html 源代码,但似乎无法在 findall 语句中使用引号 (")。由于某些无法更改的要求,我无法使用外部库,例如beautifulsoup 以帮助搜索。我已将变量名称更改为搜索。

from re import *

def suncorp_find():

    # Setup to find information
    suncorp_file = open('suncorp.html')
    contents_suncorp = suncorp_file.read()

    # Search the HTMl files to find the data
    suncorp_titles = findall(r"\"event-title\">(\w )+", contents_suncorp)

    print(suncorp_titles)

suncorp_find()

我希望得到一个包含项目的列表,但我只得到一个空列表。当只搜索 event-title 时,我得到 search_titles 列表中的多个项目。

提前感谢您的帮助

<h6 class="event-title">Queensland Reds v Jaguares</h6>

你应该引用 " 符号。

from re import findall

tmp = """<some_tag name="event-title">Some text 1</some-tag>
<some_tag name="event-title">Some text 2</some-tag>
<some_tag name="event-title">Some text 3</some-tag>"""

result = findall("\"event-title\">([\w ]+)", tmp)

输出:

['Some text 1', 'Some text 2', 'Some text 3']

P.S。我建议您使用 regex test website 来验证您的表达式。

使用这个正则表达式:

suncorp_titles = findall(r"\"event-title\">(\w.*?)<", contents_suncorp)

或者为什么不在下面??我删除了 \w 检查。不知道你是不是真的需要

suncorp_titles = findall(r"\"event-title\">(.*?)<", contents_suncorp)

我接受了输入:

<h6 class="event-title">Queensland Reds v Jaguares</h6>
<h6 class="event-title">testing line two</h6>

输出:

['Queensland Reds v Jaguares', 'testing line two']