【问题标题】:Getting the match value of re.search python [duplicate]获取re.search python的匹配值[重复]
【发布时间】:2017-01-27 16:41:41
【问题描述】:

我正在使用 Jupyter 笔记本中的 python 从网络中提取一些数据。我已经拉下数据,解析并创建了数据框。我需要从数据框中的字符串中提取一个数字。我利用这个正则表达式来做到这一点:

for note in df["person_notes"]:
    print(re.search(r'\d+', note))

结果如下:

<_sre.SRE_Match object; span=(53, 55), match='89'>

我怎样才能只得到比赛号码;在这一行中将是 89。我试图将整行转换为 str()replace(),但并非所有行都具有 span=(number, number) 相等。提前谢谢!

【问题讨论】:

  • re.search(r'\d+', note).group()

标签: string python-3.x jupyter


【解决方案1】:

您可以在返回的匹配对象上使用start()end() 方法来获取字符串中的正确位置:

for note in df["person_notes"]:
    match = re.search(r'\d+', note)
    if match:
        print(note[match.start():match.end()])
    else:
        # no match found ...

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多