这是我到目前为止所做的:
import re
text = "If you want to call me, my old number was 905-343-2112 and it has
been changed to 289-544-2345"
phone = re.findall(r'((\d{3})-(\d{3})-(\d{4}))', text)
for call in phone:
print (call[0])
我猜我的正则表达式找不到电话号码不是很好,因为如果我在打印电话时取出方括号,它似乎给了我整数,然后它分解了每组数字。我怎么能抛光这段代码
答案 0 :(得分:7)
将非捕获组用于电话号码的片段:
phone = re.findall(r'((?:\d{3})-(?:\d{3})-(?:\d{4}))', text)
^^ ^^ ^^
或者更好的是,只需删除括号
phone = re.findall(r'\d{3}-\d{3}-\d{4}', text)
答案 1 :(得分:3)
你已经关闭但你不需要模式中的括号:
phone = re.findall(r'\d{3}-\d{3}-\d{4}', text)
print(phone)
# ['905-343-2112', '289-544-2345']