[英]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
我如何歸還整個號碼?
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.