在 Python 中验证多个正则表达式模式的问题

Issue Validating more than one pattern of regex in Python

我在使用正则表达式和 re.search 方法时遇到问题。预期结果是验证 phone 号码和电子邮件。我可以验证 phone 个号码或电子邮件,但是当我想同时执行这两个操作时,我只能识别 phone 个号码。

我尝试将它们分成不同的功能,只有在注释掉 phone 数字功能时才能识别电子邮件地址。

#!/usr/bin/env python3
'''regex program for retrieving phone numbers & emails from a list,
this will use 2 regex patterns. One for phone numbers & one for emails'''
import re
import sys


if len(sys.argv) < 2:
    sys.exit("Usage: run as follows: extractor.py [phone number or email address]")

string = ' '.join(sys.argv[1:])

PHONE_NUMBER = re.compile(r"""(
    (\(\d{3}\))?|(\d{3})    # area code check
    (\d{3})                 # First 3 digits
    (\s|-|\.)               # Hyphen
    (\d{4})                 # Last 4 digits
    )""", re.VERBOSE)       # Verbose method
# \d{3}\)\d{3}-\d{4}'))

EMAIL = re.compile(r"""(
    [a-zA-Z0-9._%&+-]+      # email userid
    @                       # @ sign for email domain
    [a-zA-Z0-9.-]+          # domain
    (\.[a-zA-Z0-9]{2,3})    # dot.com/etc, a range of 2-3
    )""", re.VERBOSE)


def phone_num_email():
    '''phone numbers or email addresses'''
    if(re.search(PHONE_NUMBER, string)):
        print("Found a match for a phone number")
    elif re.search(EMAIL, string):
        print("Found a match for email address")
    else:
        print("No matches found for a phone number or email address")


# TODO:
# recognized email, still has blank acceptance of phone numbers


if __name__ == '__main__':
    phone_num_email()

您错误地使用了 if 语句来达到预期的结果。

if(re.search(PHONE_NUMBER, string)):
        print("Found a match for a phone number")
elif re.search(EMAIL, string):
        print("Found a match for email address")

您是说如果找不到 phone 号码,您只想搜索电子邮件。这是由于 else if。在搜索两者的情况下,您不想使用 else 语句,因为如果找到 phone 号码匹配,它将忽略电子邮件。

改为:

if re.search(PHONE_NUMBER, string):
        print("Found a match for a phone number")
if re.search(EMAIL, string):
        print("Found a match for email address")
else:
        print("No matches found for a phone number or email address")