Skip to content

Instantly share code, notes, and snippets.

@aambrioso1
Created June 20, 2019 18:02
Show Gist options
  • Save aambrioso1/fb0d25e8bf241d70d289368fdf067716 to your computer and use it in GitHub Desktop.
Save aambrioso1/fb0d25e8bf241d70d289368fdf067716 to your computer and use it in GitHub Desktop.
Regex.py
import re
"""
This program demonstrates two regexes: one for matching vowels and one for matching social socurity numbers (SSN's'). The program requests some text from the user to use to demo the vowel matching. For the SSN matching, the text assigned to text3 is searched for SSN's.
"""
print('Input some text.\n')
text = input()
# A regex for matching vowels.
vowelRegex = re.compile(r'[aeiouAEIOU]')
mo = vowelRegex.findall(text)
print(f"\nThe vowels in \"{text}\" are:\n\n {mo}\n")
text2 ='Here are some SSNs 123 24 1234, 456.76.5678, 987-76-1234, 299-12.8888, and 555.67 1111.'
# A regex for matching SSN's. Each SSN is broken up into groups by the parenthesis so that the groups can be reassembled in a standard form. '
SSNRegex = re.compile(r'''(
(\d{3}) # first 3 digits
(\s|-|\.) # separator
(\d{2}) # middle 2 digits
(\s|-|\.) # separator
(\d{4}) # last 4 digits
)''', re.VERBOSE)
# Any text in the file which has a typical email or phone number will be appending to the list matches. We begin with an empty list.
matches = []
# Note that the SSN's are formatted nicely wirh hyphen before they are stored in matches.'
for groups in SSNRegex.findall(text2):
SSN = groups[1]+'-'+groups[3]+'-'+groups[5]
matches.append(SSN)
# Now the program prints out the emails and phone numbers found nearly to the standard output..
if len(matches) > 0:
print(f"The SSN numbers in \"{text2}\" are:\n")
print('\n'.join(matches))
else:
print('No SSN numbers.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment