使用正则表达式匹配字符串

时间:2017-11-08 13:29:17

标签: python regex

我正在尝试匹配文字中的所有电话号码。

https://pythex.org/?regex=%5C%2B%3F(%5Cd*)%5Cs%3F%5C(%3F(%5Cd*)%5C)%3F%5Cs%3F(%5Cd*)%5B%5Cs-%5D%3F(%5Cd*)%5Cs%3F(%5Cd*)%5Cs%3F(%5Cd*)%5Cs%3F&test_string=(510)%20588-3915%0A%2B1%20(510)%20879-4700%0A%2B1(888)654-0143%0A%2B1(919)277-2172%0A%2B1(866)707-7709%0A%2B1(919)597-7014%0A%2B44%20(0)%2020%208435%206555%0A%2B44%20(0)%2020%208435%206555%0A%2B33%201%2070%2070%2096%2061%0A%2B41%20(44)%20595%2094%2001%0A%2B32%20(9)%20277%2094%2021%0A%2B34%20(0)%20931%20790%20659%0A045%204750666%0A%2B41%2044%20595%2094%2001%0A%2B31%20(0)%2020%20262%203824%20okay.2%0A%2B31%20478-511014%0A%2B32%209%20277%2094%2021%0A%2B91%20900%20133%205555&ignorecase=0&multiline=0&dotall=0&verbose=0

这个正则表达式适合我。当我检查正则表达式匹配网站时。但是当我在实际代码中使用时,它会给我错误的结果

>>> text = 'my phone is +31 478-511014 and +91 900 133 5555'
>>> mobile = re.findall(r'\+?(\d*)\s?\(?(\d*)\)?\s?(\d*)[\s-]?(\d*)\s?(\d*)\s?(\d*)\s?', text)
>>> mobile
[('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('31', '478', '', '511014', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('91', '900', '133', '5555', '', ''), ('', '', '', '', '', '')]

我做错了吗?

2 个答案:

答案 0 :(得分:1)

如果您遇到问题,这个应该有用:

[(+\d]\d[-\d\s()]*\d

答案 1 :(得分:0)

如果您将其中一个替换为+

,它就可以正常工作

mobile = re.findall(r' +?(\ d +)\ s?(?(\ d *))?\ s?(\ d *)[\ s - ]?(\ d *) \ s?(\ d *)\ s?(\ d *)\ s?',text)