Python Regular Expressions
Python Regular Expressions
Python Regular Expressions
The regular expressions can be defined as the sequence of characters which are used to
search for a pattern in a string. The module re provides the support to use regex in the
python program. The re module throws an exception if there is some error while using
the regular expression.
1. import re
Regex Functions
The following regex functions are used in the python.
SN Function Description
1 match This method matches the regex pattern in the string with the optional
flag. It returns true if a match is found in the string otherwise it
returns false.
2 search This method returns the match object if there is a match found in the
string.
3 findall It returns a list that contains all the matches of a pattern in the string.
4 split Returns a list in which the string has been split in each match.
Meta-Characters
Metacharacter is a character with the specified meaning.
Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.
Character Description
\S It returns a match if the string doesn't contain any white space character.
\Z Returns a match if the specified characters are at the end of the string.
Sets
A set is a group of characters given inside a pair of square brackets. It represents the
special meaning.
SN Set Description
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.findall("How", str)
6.
7. print(matches)
8.
9. print(matches)
Output:
['How', 'How']
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(type(matches))
8.
9. print(matches) #matches is the search object
Output:
<class '_sre.SRE_Match'>
<_sre.SRE_Match object; span=(0, 3), match='How'>
1. span(): It returns the tuple containing the starting and end position of the
match.
2. string(): It returns a string passed into the function.
3. group(): The part of the string is returned where the match is found.
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(matches.span())
8.
9. print(matches.group())
10.
11. print(matches.string)
Output:
(0, 3)
How
How are you. How is everything