简体   繁体   English

什么是RegEx可以在Python中查找电话号码?

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

I am trying to make a regex in python to detect 7-digit numbers and update contacts from a .vcf file. 我正在尝试在python中制作一个正则表达式来检测7位数字并更新.vcf文件中的联系人。 It then modifies the number to 8-digit number (just adding 5 before the number).Thing is the regex does not work. 然后将数字修改为8位数字(仅在数字前加5)。正则表达式不起作用。

I am having as error message "EOL while scanning string literal" 我收到错误消息“扫描字符串文字时停产”

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()       

I am suspecting that my regex is not in the correct format for detecting a particular pattern of numbers with 2 digits which have a particular format like the 25x and 29x and 5 digits that can be any pattern of numbers.. (TOTAL 7 digits) 我怀疑我的正则表达式的格式不正确,无法检测具有2位数字的特定数字模式,该数字具有25x和29x以及5位数字的特定格式,可以是任何数字模式。(共7位数字)

can anyone help me out on the correct format to adopt for such a case? 有人可以帮助我选择适合这种情况的正确格式吗?

/I is not how you give modifiers for regex in python. /I不是您如何在python中为正则表达式提供修饰符。 And neither you do substitution like s/// . 而且您都不会像s///那样进行替换。

You should use re.sub() for substitution, and give the modifier as re.I , as 2nd argument to re.compile : 您应该使用re.sub()进行替换,并将修饰符指定为re.I ,作为re.compile第二个参数:

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

And then for a string s , the substitution would look like: 然后对于字符串s ,替换将类似于:

re.sub(reg, replacement, s)

As such, your regex looks weird to me. 因此,您的正则表达式对我来说很奇怪。 If you want to match 7 digits numbers, starting with 25 or 29 , then you should use: 如果要匹配以2529开头的7位数字,则应使用:

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

And for replacement, use "5\\1" . 并使用"5\\1"进行替换。 In all, for a string s , your code would look like: 总而言之,对于字符串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