如何在Python中从带空格和破折号的字符串中提取数字

-1 投票
4 回答
41 浏览
提问于 2025-04-14 15:32

我正在尝试从一个字符串中提取电话号码,也就是只提取数字,这个字符串可能包含破折号、括号、空格等等。

问题是,print(f"number: {match}") 返回了一个空列表。

我的代码:

import re

number_pattern = re.compile(r'\d{10}')
match = number_pattern.findall('(289)925-4 931')
print(f"number: {match}")
if match: 
    match = ''.join(match)
    if len(match) > 9:
        print("digits: " + match)

4 个回答

0

正如@BoppreH提到的,你的代码使用re.compile(r'\d')会运行得很好。另一种方法是使用re.sub,把所有不是数字的字符(\D)替换成空字符串:

import re
          
digits = re.sub(r'\D', '', '(289)925-4 931')
print(f'digits: {digits}')

digits: 2899254931
0

与其去捕捉你想要的内容,不如先排除你不想要的内容:

>>> import re
>>> ''.join(re.split(r'\D', '(289)925-4 931'))
'2899254931'

如果你想要一个测试,确保你匹配的总共只有10个数字,否则整个匹配就不算有效,我会这样做:

>>> tgt='(289)925-4 931'
>>> phone=fd if len(fd:=''.join(re.findall(r'\d', tgt)))==10 else ''
>>> phone
'2899254931'
>>> tgt='(289)925-4 93'
>>> phone=fd if len(fd:=''.join(re.findall(r'\d', tgt)))==10 else ''
>>> phone
''
2

问题在于你的正则表达式在寻找10个连续的数字({10})。把这个部分去掉,它就能正常工作了。

其实根本不需要用正则表达式:

print(''.join(c for c in '(289)925-4 931' if c.isdigit()))
# '2899254931'

撰写回答