【问题标题】:Python regex is correct but returning None [duplicate]Python 正则表达式是正确的,但返回 None [重复]
【发布时间】:2019-12-08 05:07:37
【问题描述】:

我的正则表达式必须从字符串中识别联系人号码。这是正确的,我已经在网上对我的样本进行了测试,这里是它的例子https://regex101.com/r/Q2Z6fy/1。但是当我在我的python代码中运行它时。它不返回任何内容

这是应该正确识别字符串匹配的代码。

import regex as re
txt = '+92 42 111-865-865'
rest = re.match("^(?:(?:\(\+92\)|\+92) (?:42|332)|0332) ?\d+(?:([ -])\d+(?:\1\d+)*)?$", txt)
print rest.groups()

预期结果是字符串本身,但正则表达式返回无。

【问题讨论】:

  • import regex as re ?错了。
  • 使用import re
  • @GreenCloakGuy 即使我使用 import re 也是一样的结果。
  • @Austin import re 也返回相同的结果
  • 在定义正则表达式时使用原始字符串文字或使用\\1 而不是\1。我怀疑你想打印rest.group(),而不是rest.groups()。见demo

标签: python regex


【解决方案1】:

使用re.findall() 而不是re.match()

使用下面的代码

import re

regex = r"(?:(?:\(\+92\)|\+92) (?:42|332)|0332) ?\d+(?:([ -])\d+(?:\1\d+)*)?"

test_str = ("+92 42 111-865-865\n"
            "(+92) 42 3256 0445\n"
            "03325138889\n"
            "0332 5138889\n"
            "+92 332 5138889\n"
            "+92 3325138889\n\n"
            "48358982872144\n"
            "100220100\n"
            "36470002")

matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
    for groupNum in range(0, len(match.groups())):
        print(match.group(groupNum))

【讨论】:

  • 它返回空列表
  • 你需要修复你的正则表达式模式
  • @UmairRashid 我已经在我的输入中对其进行了测试:regex101.com/r/Q2Z6fy/1
  • @mohartechnology 查看我的更新答案
  • 感谢这是正确的。我使用的是 match.groups() 而不是 match.group()
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 2019-04-20
  • 2017-06-25
  • 2019-06-16
  • 1970-01-01
  • 2012-08-22
  • 2018-03-14
  • 1970-01-01
相关资源
最近更新 更多