【问题标题】:Issue in finding email id from a string - Python从字符串中查找电子邮件 ID 的问题 - Python
【发布时间】:2020-11-09 18:04:49
【问题描述】:

谁能帮我弄清楚下面的代码有什么问题:

import re

class RegexTest(object):
    
    def regex_test(self, reg, string):
        reg_pattern = repr(reg)[1:-1]
        match = re.search(reg_pattern, string)
        if (match is not None):
            return match.group(0)
        else:
            return None
        
test = RegexTest()
print(test.regex_test('[A-Za-z0-9\._]+\@\w+\.\w{2,4}', 'My email id is: abcd123_hello@yahoo.com'))

输出:

None

任何帮助将不胜感激。

【问题讨论】:

  • 删除reg_pattern = repr(reg)[1:-1],使用match = re.search(reg, string)
  • 您好 Mahesh_Vkm,欢迎来到 stackoverflow。请尝试解释您的代码应该做什么,以及它与实际结果有何不同。如果用户不必仅从您的代码中重建它,他们将不胜感激。

标签: python regex email


【解决方案1】:

如果您打印您在 regex_test 方法中创建的正则表达式模式,您将看到您使用的不是文字字符串模式本身,而是转换为文字文本的字符串文字。这意味着,模式中的所有反斜杠都变为双倍,并且正则表达式模式中的 \\ 与文字 \ 字符匹配。

看:

print(repr(reg)[1:-1])
# => [A-Za-z0-9\\._]+\\@\\w+\\.\\w{2,4}
print(reg)
# => [A-Za-z0-9\._]+\@\w+\.\w{2,4}

使用

def regex_test(self, reg, string):
    match = re.search(reg, string)
    if match is not None:
        return match.group(0)
    else:
        return None

您不需要将if 条件用括号括起来。

在定义模式时,建议使用原始字符串文字,并且您不需要在字符类中转义 .@ 字符:

print(test.regex_test(r'[A-Za-z0-9._]+@\w+\.\w{2,4}', 'My email id is: abcd123_hello@yahoo.com'))

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 2013-03-20
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多