从电话号码字符串中删除不需要的字符

2024-10-01 17:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是正则表达式代码,以抓取电话号码和删除不需要的字符。在

import re
strs = 'dsds +48 124 cat cat cat245 81243!!'
match = re.search(r'.[ 0-9\+\-\.\_]+', strs)

if match:                      
    print 'found', match.group() ## 'found word:cat'
else:
    print 'did not find'

它只返回:

^{pr2}$

我怎么能把整个数字还回来?在


Tags: 代码importre目标searchifmatch电话号码
3条回答

这是我用来替换所有非数字的一个单一的 连字符,似乎对我有用:

# convert sequences of non-digits to a single hyphen
fixed_phone = re.sub("[^\d]+","-",raw_phone)

您想使用^{},而不是search()

>>> strs = 'dsds +48 124 cat cat cat245 81243!!'
>>> re.sub(r"[^0-9+._ -]+", "", strs)
' +48 124   245 81243'

[^0-9+._ -]negated character class^在这里很重要-这个表达式的意思是:“匹配一个既不是数字,也不是加号、点、下划线、空格或破折号的字符”。在

+告诉regex引擎匹配前面标记的一个或多个实例。在

re.sub()的问题是,在最后的电话号码字符串中会有额外的空格。非正则表达式方式,返回正确的电话号码(不含空格):

>>> strs = 'dsds +48 124 cat cat cat245 81243!!'
>>> ''.join(x for x in strs if x.isdigit() or x == '+')
'+4812424581243'

相关问题 更多 >

    热门问题