Python中的电话号码正则表达式(Regex) [英] Phone Number Regular Expression (Regex) in Python
问题描述
深入研究python提供了一个有关创建电话号码正则表达式的精彩小教程: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers
Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers
最终版本看起来像:
phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$', re.VERBOSE)
这对于我可以提出的几乎所有示例都很好,但是我发现了一个我似乎无法解决的重大失败.
This works fine for almost all examples I can come up with, however I found a pretty big failure that I can't seem to fix.
如果一组3位数字位于电话号码之前,则可以正常工作. IE: 关闭500美元,致电123-456-7891"
If a group of 3 digits comes before the phone number it works fine. IE: "500 dollars off, call 123-456-7891"
如果一组3位数字出现在电话号码之后,则它失败. IE: 致电123-456-7891可获得最高500的折扣"
If a group of 3 digits comes after the phone number it fails. IE: "Call 123-456-7891 for a discount of up to 500"
对同时适用于两个示例的修复程序有何想法?
Any ideas on a fix that would work for both examples?
推荐答案
(\d*)$
要求您要匹配的字符串以数字字符结尾($
表示行尾").如果您要匹配的较大字符串(电话号码可能不在行尾),请尝试删除$
.
The (\d*)$
requires that the string you're matching against end with digit characters (the $
signifies "end of line"). Try removing the $
if you're matching against a larger string where the phone number may not be at the end of the line.
这篇关于Python中的电话号码正则表达式(Regex)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!