RegEx /Regular Expressions for Python (Python Part 17)

This class shows you how to use regex to match specific patterns such as email addresses, ip addresses and MAC addresses in strings

  • 00:00 Intro
  • 06:45 Resources for Learning RegEx
  • 13:27 Basic RegEx Patterns
  • 22:14 Basic RegEx Email Pattern
  • 27:58 RegEx for IP Addresses
  • 34:17 Search Function
  • 37:11 Lab – Find FQDN IP Address with RegEx
  • 42:34 Final Thoughts

regex-basic.py

import re

message = 'bob says bamb in a barn as a bat barks at a bub'
print(message)

pattern = r'b.b'
print(re.findall(pattern, message))

pattern = r'b.*b'
print(re.findall(pattern, message))

pattern = r'b.*?b'
print(re.findall(pattern, message))

pattern = r'\bb.*?b\b'
print(re.findall(pattern, message))

pattern = r'b[A-Za-z]+b'
print(re.findall(pattern, message))

regex-email.py

import re

message = 'bob1@aol.com frank tod@aol.com sue phil@gmail'

result = re.findall(r'[A-Za-z0-9]+@[A-Za-z]+\.[A-Za-z]+', message)

print(result)

regex-ip.py

import re

ip_message = ‘ the ip address is 192.168.1.1 and 10.1.10.1’

pattern = r'[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{0,3}’
ip_result = re.findall(pattern, ip_message)
print(ip_result)

pattern = r’\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}’
ip_result = re.findall(pattern, ip_message)
print(ip_result)

pattern = r’\b(?:\d{1,3}.){3}\d{1,3}\b’
ip_result = re.findall(pattern, ip_message)
print(ip_result)

regex-search.py

import re

message = 'my paswrd is 123456'

if re.search('pas[a-z]+rd', message):
    print(message)
else:
    print('No Password')

regex-demo.py

import os
import re

site = 'cnn.com'
command = f'ping -c 1 {site}'
response = os.popen(command).read()

#print(response)

pattern = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
ip_result = re.findall(pattern, response)
print(f'{site} IP Address is {ip_result[0]}')

Be the first to comment

Leave a Reply