A Regular Expression (RegEx) is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.
Python has a built-in package called re, which can be used to work with Regular Expressions.
re ModuleTo use regular expressions, you must first import the re module:
import re
The re module offers a set of functions that allows us to search a string for a match:
re.search()The search() function searches the string for a match, and returns a Match object if there is a match.
import retxt = "The rain in Spain" x = re.search("^The.*Spain$", txt)
if x: print("YES! We have a match!") else: print("No match")
re.findall()The findall() function returns a list containing all matches.
import retxt = "The rain in Spain" x = re.findall("ai", txt)
print(x) // Output: ['ai', 'ai']
re.split()The split() function returns a list where the string has been split at each match.
re.sub()The sub() function replaces the matches with the text of your choice.
import retxt = "The rain in Spain" x = re.sub("\s", "9", txt)
print(x) // The9rain9in9Spain
Metacharacters are characters with a special meaning. Here are a few essential ones:
[] A set of characters (e.g. "[a-m]")\ Signals a special sequence (can also be used to escape special characters). Any character (except newline character)^ Starts with$ Ends with* Zero or more occurrences+ One or more occurrences? Zero or one occurrences{} Exactly the specified number of occurrences