簡體   English   中英

從電話號碼字符串中刪除不需要的字

[英]Remove unwanted characters from phone number string

我的目標是使用正則表達式代碼來獲取電話號碼並刪除不需要的字符。

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'

它僅返回:

+48 124 

我如何歸還整個號碼?

你想使用sub() ,而不是search()

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

[^0-9+._ -]是一個否定的字符類 這里的^很重要 - 這個表達式意味着:“匹配既不是數字,也不是加號,點,下划線,空格或短划線的字符”。

+告訴正則表達式引擎匹配前一個令牌的一個或多個實例。

re.sub()的問題在於您在最終的電話號碼字符串中獲得了額外的空格。 非正則表達式方式,返回正確的電話號碼(沒有任何空格):

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

這就是我用單個連字符替換所有非數字的方法,它似乎對我有用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM