python - 匹配美国电话号码的正则表达式

标签 python regex

我有一些(有点)工作代码来匹配以下格式的美国电话号码:###-###-####

问题是,对于我的 phone_numbers 中的每个 phone_number,我的代码只是点击代码中的 else block :

file = open("results.txt", "w")
rgxpattern = '^[0-9]{3}-[0-9]{3}-[0-9]{4}$'
regexp = re.compile(rgxpattern)

for phone_number in phone_numbers:
    phone_number = str(phone_number)
    if regexp.match(phone_number):                      
        file.write('\n')
        file.write(str(phone_number))
    else:
        file.write('BAD#')

我上面的 rgxpattern 有问题吗?我试过使用:

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

^\d{3}-\d{3}-\d{4}$

示例电话号码:

 111-222-3333  
 777-444-4444  

结果摘录:

BAD#BAD#BAD#BAD#

有什么想法或帮助吗?

最佳答案

如果您的“示例电话号码”是准确的,那么每个电话号码前后都有空格,这应该可以解决问题:

^\s*\d{3}-\d{3}-\d{4}\s*$

关于python - 匹配美国电话号码的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938152/

相关文章:

ios - 在 Swift 中从字符串中提取某些文本

java - 我需要帮助使正则表达式正确

javascript - 正则表达式可选的非捕获组

python - boxPoints 返回负 y 值

python - 检查 Python 中的类型

python - 如果特定键的值相同,则合并字典

python - 允许在我的正则表达式中使用转义序列

python - 如何在 python 中使用正则表达式替换模式?

python - 如何更有效地解码 RSA 加密?

python - 从python脚本获取shell脚本 "read"值