python正则表达式提取电话号码_用于提取电话号码的正则表达式

我不熟悉正则表达式,我正在尝试编写电话号码的模式,以便识别它们并能够提取它们。我的疑问可以归纳为以下几个简单的例子:

我首先尝试确定字符串中是否有类似(+34)的内容,这应该是可选的:prefixsrch = re.compile(r'(\(?\+34\)?)?')

我用以下方法在以下字符串中进行测试:

^{pr2}$

结果是:['(+34)','']

My first question is: why does it find two occurrences of the pattern? I guess that this is related to the fact that the prefix thing is optional but I do not completely understand it. Anyway, now for my big doubt

如果我们用类似的方法搜索9位数的模式,我们得到的结果是一样的:numsrch = re.compile(r'\d{9}')

line1 = "971756754"

print numsrch.findall(line1)

产生如下结果:['971756754']

这很好。现在我要做的是识别一个9位数的数字,不管前面有没有(+34)。所以据我所知,我应该做些类似的事情:phonesrch = re.compile(r'(\(?\+34\)?)?\d{9}')

如果我在下面的字符串中测试它。。。在line0 = "(+34)971756754"

line1 = "971756754"

print phonesrch.findall(line0)

print phonesrch.findall(line1)

令我惊讶的是,我得到的是:

['(+34)']

['']

我希望得到的是['(+34)971756754']和['971756754']。有人知道这个吗?事先非常感谢。在

你可能感兴趣的:(python正则表达式提取电话号码_用于提取电话号码的正则表达式)