Advertisement
Dornyel

no regex here

Oct 23rd, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. def is_phone_number(text): # test program to find U.S. phone numbers in a string
  2.     if text[0].isdecimal():
  3.         if len(text) != 12:
  4.             return False # not the right length
  5.         for i, char in enumerate(text):
  6.             if i == 3 or i == 7:
  7.                 if char != "-":
  8.                     return False # index not hyphen
  9.             elif not char.isdecimal():
  10.                 return False # index is not integer
  11.         return True # string matches general criteria for a U.S. phone number
  12.     if text[0] == "(":
  13.         if len(text) != 14:
  14.             return False
  15.         for i, char in enumerate(text):
  16.             if i == 0:
  17.                 if char != "(":
  18.                     return False # index is not bracket
  19.             elif i == 4:
  20.                 if char != ")":
  21.                     return False # index is not bracket
  22.             elif i == 5:
  23.                 if char != " ":
  24.                     return False # index is not whitespace
  25.             elif i == 9:
  26.                 if char != "-":
  27.                     return False # index is not hyphen
  28.             elif not char.isdecimal():
  29.                 return False # index is not integer
  30.         return True # string matches general criteria for a U.S. phone number
  31.    
  32. message = "Call me at 415-555-1345 this afternoon, or tomorrow at (415) 555-3612 for my office line."
  33.  
  34. found_number = False
  35.  
  36. for i in range(len(message)):
  37.     chunk = message[i:i+12]# takes a chunk of 12 characters out of the string, shifting by one character each time
  38.     if is_phone_number(chunk):
  39.         print(f"Found phone number {chunk} in the message.")
  40.         found_number = True
  41.     chunk2 = message[i:i+14]# takes a chunk of 12 characters out of the string, shifting by one character each time
  42.     if is_phone_number(chunk2):
  43.         print(f"Found phone number {chunk2} in the message.")
  44.         found_number = True
  45. if not found_number:
  46.     print("Could not find any phone numbers in the string.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement