【问题标题】:Regex not returning full match, just the start正则表达式不返回完整匹配,只是开始
【发布时间】:2023-01-25 04:24:48
【问题描述】:

我希望此正则表达式返回全文加数字,例如Indy-500 或 Independent-500,但它似乎将其砍掉。

re.findall('(Independent|Indy)-\d+', "在 Indy-500 或 Independent-1000 中有一家公司")

--> ['独立', '独立']

我怎样才能解决这个问题?如果我只搜索Indy-\d+,它就可以完美运行,例如

re.findall('Indy-\d+', "在 Indy-500 或 Independent-1000 中有一家公司")

--> ['Indy-500']

但我希望它匹配一系列前缀。

【问题讨论】:

  • 使用非捕获组:re.findall(r'(?:Independent|Indy)-\d+', "In the Indy-500 or Independent-1000 there was a company")

标签: regex python-re python-regex


【解决方案1】:

使用非捕获组来阐明备选方案:

>>> re.findall('(?:Independent|Indy)-d+', "In the Indy-500 or Independent-1000 there was a company")
['Indy-500', 'Independent-1000']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多