Regex
ipynb4 kBPython · 7 cellsExtra material of chapter 2
import re
pattern = r'Car '
text = r'''
Here is the car of the future! This car is the opposite of todays' cars;
today's cars are noisy and dirty, this one is silent and clean.
Today's cars have wheels, this one does not. It moves like a snail, but much faster than a snail !
'''
result = re.findall(pattern, text)
print(result)[]
import re
pattern = r"\d{4}"
text = r'''
However you probably won't ever drive a "snail car",
even if you're under 20 today.
This, perhaps, is the car of the year 2100,
the car that your grandchildren will maybe drive.
'''
result = re.findall(pattern, text)
print(result)['2100']
import re
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
text = r'''
Here is my email address: aalaaeddein@gmail.com
I have another email address: Test.2@gmail.com
Here is my Outlook email: Test_1994@outlook.gov
'''
result = re.findall(pattern, text)
print(result)
['aalaaeddein@gmail.com', 'Test.2@gmail.com', 'Test_1994@outlook.gov']
import re
pattern = r"\(?\+?\d*\)? *\d\d *-? *\d\d\d *\d\d\d"
text = r'''
Here is my phone number: 78888222
I have another number: 76 - 443 222
If you want to contact from outside Lebanon use this: (+961) 71 321123
'''
result = re.findall(pattern, text)
print(result)
[' 78888222', ' 76 - 443 222', '(+961) 71 321123']
import re
pattern = r"(?:(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9][0-9])|(?:[0-9][0-9])|(?:[0-9]))\.){3}(?:(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9][0-9])|(?:[0-9][0-9])|(?:[0-9])))"
text = r'''
19.232.111.0
222.265.111.111
132.1333.211.11
19.1.9.8
1.0.0.255
1.55.90.190
8.2.190
'''
result = re.findall(pattern, text)
print(result)['19.232.111.0', '19.1.9.8', '1.0.0.255', '1.55.90.190']