【发布时间】:2018-09-26 14:48:41
【问题描述】:
所以我试图从文件中读取电话号码,但如果我在末尾添加额外的号码,我无法让它处理号码 例如:(123) 456-7890 很好,但 (123) 456-7890123 也可以通过。最后如何检查多余的数字。
import re # Import Real Expressions
def isValid(s):
Filter1 = re.compile("[0-9]{3}\-[0-9]{3}\-[0-9]{4}") #Test for format xxx-xxx-xxxx
return Filter1.match(s) #return true if matches format
def isValid2(s):
Filter2 = re.compile("\([0-9]{3}\) [0-9]{3}\-[0-9]{4}") #Test for format (xxx) xxx-xxxx
return Filter2.match(s)# return true if matches format
def findValidPhone():
filename = "input1.txt" #delcare filename
with open(filename,"r") as inFile: #openfile
for line in inFile: #for all the lines in the file
s = line # store the line as a variable
# print(s)
if ( isValid(s)): #run tests using function isValid if true print number
print(s)
elif(isValid2(s)): #run test using function isValid2 if true print number
print(s)
else: # print invalid number if an invalid number is found in the file
print("Invalid Number")
inFile.close() #close the file
findValidPhone() #function call
【问题讨论】:
-
你可能想要在你的正则表达式中使用
^和$,你也只想编译一次而不是每次都编译
标签: python phone-number