[ SRE_ARENA ]
REGEX, EXCEPTIONS & INPUT

Pattern Matching & Safety Nets.

Implementation Code: 1. RegEx (Regular Expressions)
PYTHON
import re

log = "Error in module at 10:45 AM"

# .search() finds the first match
x = re.search("^Error.*AM$", log)
if x:
    print("Match found!")

# .findall() returns a list of all matches
text = "The rain in Spain"
x = re.findall("in", text)
print(x) # ['in', 'in', 'in']

# Extracting an IP address
ip_log = "Connection from 192.168.1.1 failed"
ip = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", ip_log)
print(ip.group()) # 192.168.1.1
DOWNLOADING CONCEPT: 1. REGEX (REGULAR EXPRESSIONS)...
  • ↳A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
  • ↳Python has a built-in package called re, which can be used to work with Regular Expressions.
  • ↳re.findall() returns a list containing all matches.
  • ↳re.search() returns a Match object if there is a match anywhere in the string.
  • ↳re.sub() replaces one or many matches with a string.

↳You use Metacharacters to define the pattern: ^ (Starts with), $ (Ends with), * (Zero or more), + (One or more), ? (Zero or one), {} (Exactly the specified number of occurrences).

▲ LIVE INCIDENTExtract the IP address from this log string.
sre@arena:~/python-regex-exceptions
sre@arena:~$ python -c "import re; log='Error at 192.168.1.5'; print(re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', log).group())"