Recommended Books

Python Regex



Python Regex, or “Regular Expression”, is a sequence of characters that define a search pattern. This search pattern is then used to perform operations on strings, such as “find” or “find and replace”.

In short, Regex can be used to check if a string contains a specified string pattern.

Start of by importing the regex library, re.

import re

Meta Characters

Meta characters are characters that symbolize patterns or formats. Below is list of them, and what they represent.

CharacterDescription
[]Represents a set of characters
.Any character (Except for new line characters)
+One or more occurrences
*Zero or more occurrences
{}A fixed number of occurrences
^Starts with
$Ends with
|Either/Or

Re.match Function

To demonstrate the use of the above characters, we’ll be using the re.match function. This function takes two inputs, the pattern and the string on which the pattern is to be applied.

re.match(pattern, string)

If the match was successful, a match object is returned, else None is returned.


Re.findall Function

To demonstrate the use of the above characters, we’ll be using the re.findall function. This function takes two inputs, the pattern and the string on which the pattern is to be applied.

re.findall(pattern, string)

This function returns a list of all the matches found within the string.

Character: []

Sample = "Hello World"
Sample2 = "This website is called CodersLegacy"

print(re.findall("[a]", Sample))
print(re.findall("[a-z]", Sample))
print(re.findall("[a]", Sample2))
print(re.findall("[aoiue]", Sample2))
#OUTPUT 
[]
['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']
['a', 'a']
['i', 'e', 'i', 'e', 'i', 'a', 'e', 'o', 'e', 'e', 'a']

Character: .

Character: +

Character: *

Character: {}

Character: ^

Character: $

Character: |