让正则表达式在电话号码中包含分机号时出现问题

时间:2019-06-15 23:27:52

标签: python

我正在尝试从文件中打印带有扩展名的电话号码的正则表达式。此代码可以使电话号码本身完全正常。打印扩展名是给我的问题。该代码应从文本文件中提取文本,然后遍历并查找带有扩展名以及电子邮件的电话号码。

import os, re, zipfile
phoneRegex = re.compile(r'''
    [0-9]{3}                # area code
    \s?[-.]                        # separator
    [0-9]{3}                           # first 3 digits
    \s?[-.]                         # separator
    [0-9]{4}                           # last 4 digits
    \s?(ext)\s?\d{2,5}''', re.VERBOSE) #allows for whitespace




# Create email regex.
emailRegex = re.compile(r'''
      [a-zA-Z0-9._%+-]+      # username
      @                      # @ symbol
      [a-zA-Z0-9.-]+         # domain name
       \.[a-zA-Z]{2,4}     # dot-something
       ''', re.VERBOSE)     #allows for whitespace   

name1 = input('Enter the name of the input file: ')
print('Input file name is ' + name1 + '!')


iFile = open(name1)


matches = []

for line in iFile:
    matches += phoneRegex.findall(line)

    #matches += emailRegex.findall(line)



print(matches)

iFile.close()
print('')
print('')


name2 = input('Enter the name of the output file: ')
print('Output file name is ' + name2 + '!')

oFile = open(name2, 'a')




for i in matches:
    oFile.write(i + '\n')


oFile.close()

0 个答案:

没有答案