RegEx
Python RegEx
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re
, which can be used to work with Regular Expressions.
Import the re module:
RegEx in Python
When you have imported the re module, you can start using regular expressions:
Example
RegEx Functions
The re
module offers a set of functions that allows us to search a string for a match:
Function
Description
findall
Returns a list containing all matches
search
Returns a Match object if there is a match anywhere in the string
split
Returns a list where the string has been split at each match
sub
Replaces one or many matches with a string
Metacharacters
Metacharacters are characters with a special meaning:
Example 1: re.findall()
If the pattern is not found, re.findall() returns an empty list.
Example 2: re.split()
If the pattern is not found, re.split() returns a list containing the original string.
Example 3: re.sub()
If the pattern is not found, re.sub() returns the original string.
More details can be found in Regular expression operations and Regular Expression HOWTO
Last updated