簡體   English   中英

什么是RegEx可以在Python中查找電話號碼?

[英]What is a RegEx to find phone numbers in Python?

我正在嘗試在python中制作一個正則表達式來檢測7位數字並更新.vcf文件中的聯系人。 然后將數字修改為8位數字(僅在數字前加5)。正則表達式不起作用。

我收到錯誤消息“掃描字符串文字時停產”

regex=re.compile(r'^(25|29|42[1-3]|42[8-9]|44|47[1-9]|49|7[0-9]|82|85|86|871|87[5-8]|9[0-8])/I s/^/5/')

#Open file for scanning
f = open("sample.vcf")

#scan each line in file
for line in f:
    #find all results corresponding to regex and store in pattern
    pattern=regex.findall(line)
#isolate results
    for word in pattern:
        print word
        count = count+1 #display number of occurences
        wordprefix = '5{}'.format(word)
        s=open("sample.vcf").read()
        s=s.replace(word,wordprefix)
        f=open("sample.vcf",'w')
        print wordprefix
        f.write(s)
        f.close()       

我懷疑我的正則表達式的格式不正確,無法檢測具有2位數字的特定數字模式,該數字具有25x和29x以及5位數字的特定格式,可以是任何數字模式。(共7位數字)

有人可以幫助我選擇適合這種情況的正確格式嗎?

/I不是您如何在python中為正則表達式提供修飾符。 而且您都不會像s///那樣進行替換。

您應該使用re.sub()進行替換,並將修飾符指定為re.I ,作為re.compile第二個參數:

reg = re.compile(regexPattern, re.I)

然后對於字符串s ,替換將類似於:

re.sub(reg, replacement, s)

因此,您的正則表達式對我來說很奇怪。 如果要匹配以2529開頭的7位數字,則應使用:

r'(2[59][0-9]{5})'

並使用"5\\1"進行替換。 總而言之,對於字符串s ,您的代碼如下所示:

reg = re.compile(r'(2[59][0-9]{5})', re.I)
new_s = re.sub(reg, "5\1", s)

暫無
暫無

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

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