【问题标题】:findall() returns empty string on html file in Python REGEXfindall() 在 Python REGEX 中的 html 文件上返回空字符串
【发布时间】:2017-01-10 19:54:03
【问题描述】:

我正在使用 Python 学习正则表达式,并且正在做谷歌正则表达式教程的婴儿名字练习。 html 文件 --baby1990.html-- 是一个压缩文件,可以在这里下载:https://developers.google.com/edu/python/set-up('下载 Google Python 练习')

年份放在标签中。 html代码如下:

<h3 align="center">Popularity in 1990</h3>

我正在使用以下代码从文件中提取年份:

f = open('C:/Users/ALEX/MyFiles/JUPYTER NOTEBOOKS/google-python-exercises/babynames/baby1990.html', 'r')

strings = re.findall(r'<h3 align="center">Popularity in (/d/d/d/d)</h3>', f.read())

我已经使用 RegularExpressions101 网站测试了该模式,并且它有效。

但是返回的“字符串”列表是空的。

len(字符串) 出去

【问题讨论】:

  • (/d/d/d/d) 更改为(\d\d\d\d)(\d{4})
  • 请澄清。 findall 是否返回空字符串或空列表?或者它是否返回一个包含一个元素的列表,它是一个空字符串?还是别的什么?
  • 仅供参考,使用正则表达式解析 HTML 通常被认为是一个非常糟糕的主意。
  • 好吧,我搞砸了。我测试了表达式,发现了 regex101 的错误,但我没有将更改传递给表达式。我有点累了。现在,它可以工作了。

标签: python regex findall


【解决方案1】:

我认为在上下文字符串中匹配年份的最佳方法是使用re.searchre.match

例如:

import re

tag = """<h3 align="center">Popularity in 1990</h3>"""

mo = re.search(r"Popularity in (\d{4})", tag)
year = mo.group(1) if mo else ""

print(year)
# -> 1990

当然,如果要查找所有匹配项,则需要使用re.findall

你检查你的Python RegEx,你也可以在线尝试https://regex101.com/

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2021-10-09
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多