![]() |
VOOZH | about |
A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a string or set of strings.
It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns.
Python has a built-in module named "re" that is used for regular expressions in Python. We can import this module by using import statement.
Importing re module in Python using following command:
import re
You can use RegEx in Python after importing re module.
Example:
This Python code uses regular expressions to search for the word "portal" in the given string and then prints the start and end indices of the matched word within the string.
Start Index: 34 End Index: 40
Note: Here r character (r’portal’) stands for raw, not regex. The raw string is slightly different from a regular string, it won’t interpret the \ character as an escape character. This is because the regular expression engine uses \ character for its own escaping purpose.
Before starting with the Python regex module let's see how to actually write regex using metacharacters or special sequences.
The re module in Python provides various functions that help search, match, and manipulate strings using regular expressions.
Below are main functions available in the re module:
| Function | Description |
|---|---|
| re.findall() | finds and returns all matching occurrences in a list |
| re.compile() | Regular expressions are compiled into pattern objects |
| re.split() | Split string by the occurrences of a character or a pattern. |
| re.sub() | Replaces all occurrences of a character or patter with a replacement string. |
resubn | It's similar to re.sub() method but it returns a tuple: (new_string, number_of_substitutions) |
| re.escape() | Escapes special character |
| re.search() | Searches for first occurrence of character or pattern |
Let's see the working of these RegEx functions with definition and examples:
Returns all non-overlapping matches of a pattern in the string as a list. It scans the string from left to right.
Example: This code uses regular expression \d+ to find all sequences of one or more digits in the given string.
['123456789', '987654321']
Compiles a regex into a pattern object, which can be reused for matching or substitutions.
Example 1: This pattern [a-e] matches all lowercase letters between 'a' and 'e', in the input string "Aye, said Mr. Gibenson Stark". The output should be ['e', 'a', 'd', 'b', 'e'], which are matching characters.
['e', 'a', 'd', 'b', 'e', 'a']
Explanation:
Example 2: The code uses regular expressions to find and list all single digits and sequences of digits in the given input strings. It finds single digits with \d and sequences of digits with \d+.
['1', '1', '4', '1', '8', '8', '6'] ['11', '4', '1886']
Example 3: Word and non-word characters
['H', 'e', 's', 'a', 'i', 'd', 'i', 'n', 's', 'o', 'm', 'e', '_', 'l', 'a', 'n', 'g'] ['I', 'went', 'to', 'him', 'at', '11', 'A', 'M', 'he', 'said', 'in', 'some_language'] [' ', ' ', '*', '*', '*', ' ', ' ', '.']
Example 4: The regular expression pattern 'ab*' to find and list all occurrences of 'ab' followed by zero or more 'b' characters. In the input string "ababbaabbb". It returns the following list of matches: ['ab', 'abb', 'abbb'].
['ab', 'abb', 'a', 'abbb']
Explanation:
Splits a string wherever the pattern matches. The remaining characters are returned as list elements.
Syntax:
re.split(pattern, string, maxsplit=0, flags=0)
Example 1: Splitting by non-word characters or digits
This example demonstrates how to split a string using different patterns like non-word characters (\W+), apostrophes, and digits (\d+).
['Words', 'words', 'Words'] ['Word', 's', 'words', 'Words'] ['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM'] ['On ', 'th Jan ', ', at ', ':', ' AM']
Example 2: Using maxsplit and flags
This example shows how to limit the number of splits using maxsplit, and how flags can control case sensitivity.
['On ', 'th Jan 2016, at 11:02 AM'] ['', 'y, ', 'oy oh ', 'oy, ', 'om', ' h', 'r', ''] ['A', 'y, Boy oh ', 'oy, ', 'om', ' h', 'r', '']
Note: In the second and third cases of the above , [a-f]+ splits the string using any combination of lowercase letters from 'a' to 'f'. The re.IGNORECASE flag includes uppercase letters in the match.
The re.sub() function replaces all occurrences of a pattern in a string with a replacement string.
Syntax:
re.sub(pattern, repl, string, count=0, flags=0)
Example 1: The following examples show different ways to replace the pattern 'ub' with '~*', using various flags and count values.
S~*ject has ~*er booked already S~*ject has Uber booked already S~*ject has Uber booked already Baked Beans & Spam
re.subn() function works just like re.sub(), but instead of returning only the modified string, it returns a tuple: (new_string, number_of_substitutions)
Syntax:
re.subn(pattern, repl, string, count=0, flags=0)
Example: Substitution with count
This example shows how re.subn() gives both the replaced string and the number of times replacements were made.
('S~*ject has Uber booked already', 1)
('S~*ject has ~*er booked already', 2)
2
S~*ject has ~*er booked already
re.escape() function adds a backslash (\) before all special characters in a string. This is useful when you want to match a string literally, including any characters that have special meaning in regex (like ., *, [, ], etc.).
Syntax:
re.escape(string)
Example: Escaping special characters
This example shows how re.escape() treats spaces, brackets, dashes, and tabs as literal characters.
This\ is\ Awesome\ even\ 1\ AM I\ Asked\ what\ is\ this\ \[a\-9\]\,\ he\ said\ \ \ \^WoW
The re.search() function searches for the first occurrence of a pattern in a string. It returns a match object if found, otherwise None.
Note: Use it when you want to check if a pattern exists or extract the first match.
Example: Search and extract values
This example searches for a date pattern with a month name (letters) followed by a day (digits) in a sentence.
Match at index 14, 21 Full match: June 24 Month: June Day: 24
Metacharacters are special characters in regular expressions used to define search patterns. The re module in Python supports several metacharacters that help you perform powerful pattern matching.
Below is a quick reference table:
MetaCharacters | Description |
|---|---|
\ | Used to drop the special meaning of character following it |
[] | Represent a character class |
^ | Matches the beginning |
$ | Matches the end |
. | Matches any character except newline |
| | Means OR (Matches with any of the characters separated by it. |
? | Matches zero or one occurrence |
* | Any number of occurrences (including 0 occurrences) |
+ | One or more occurrences |
{} | Indicate the number of occurrences of a preceding regex to match. |
() | Enclose a group of Regex |
Let's discuss each of these metacharacters in detail:
The backslash (\) makes sure that the character is not treated in a special way. This can be considered a way of escaping metacharacters.
For example, if you want to search for the dot(.) in the string then you will find that dot(.) will be treated as a special character as is one of the metacharacters (as shown in the above table). So for this case, we will use the backslash(\) just before the dot(.) so that it will lose its specialty. See the below example for a better understanding.
Example: The first search (re.search(r'.', s)) matches any character, not just the period, while the second search (re.search(r'\.', s)) specifically looks for and matches the period character.
<re.Match object; span=(0, 1), match='g'> <re.Match object; span=(5, 6), match='.'>
Square Brackets ([]) represent a character class consisting of a set of characters that we wish to match. For example, the character class [abc] will match any single a, b, or c.
We can also specify a range of characters using - inside the square brackets. For example,
We can also invert the character class using the caret(^) symbol. For example,
Example: In this code, you're using regular expressions to find all the characters in the string that fall within the range of 'a' to 'm'. The re.findall() function returns a list of all such characters. In the given string, the characters that match this pattern are: 'c', 'k', 'b', 'f', 'j', 'e', 'h', 'l', 'd', 'g'.
['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']
Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given character(s) or not. For example -
Example: This code uses regular expressions to check if a list of strings starts with "The". If a string begins with "The," it's marked as "Matched" otherwise, it's labeled as "Not matched".
Matched: The quick brown fox Matched: The lazy dog Not matched: A quick brown fox
Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given character(s) or not. For example-
Example: This code uses a regular expression to check if the string ends with "World!". If a match is found, it prints "Match found!" otherwise, it prints "Match not found".
Match found!
Dot(.) symbol matches only a single character except for the newline character (\n). For example -
Example: This code uses a regular expression to search for the pattern "brown.fox" within the string. The dot (.) in the pattern represents any character. If a match is found, it prints "Match found!" otherwise, it prints "Match not found".
Match found!
The | operator means either pattern on its left or right can match. a|b will match any string that contains a or b such as acd, bcd, abcd, etc.
The question mark (?) indicates that the preceding element should be matched zero or one time. It allows you to specify that the element is optional, meaning it may occur once or not at all.
For example, ab?c will be matched for the string ac, acb, dabc but will not be matched for abbc because there are two b. Similarly, it will not be matched for abdc because b is not followed by c.
Star (*) symbol matches zero or more occurrences of the regex preceding the * symbol.
For example, ab*c will be matched for the string ac, abc, abbbc, dabc, etc. but will not be matched for abdc because b is not followed by c.
Plus (+) symbol matches one or more occurrences of the regex preceding the + symbol.
For example, ab+c will be matched for the string abc, abbc, dabc, but will not be matched for ac, abdc, because there is no b in ac and b, is not followed by c in abdc.
Braces match any repetitions preceding regex from m to n both inclusive.
For example, a{2, 4} will be matched for the string aaab, baaaac, gaad, but will not be matched for strings like abc, bc because there is only one a or no a in both the cases.
Group symbol is used to group sub-patterns.
For example, (a|b)cd will match for strings like acd, abcd, gacd, etc.
Special sequences do not match for the actual character in the string instead it tells the specific location in the search string where the match must occur. It makes it easier to write commonly used patterns.
Special Sequence | Description | Examples | |
|---|---|---|---|
\A | Matches if the string begins with the given character | \Afor | for geeks |
for the world | |||
\b | Matches if the word begins or ends with the given character. \b(string) will check for the beginning of the word and (string)\b will check for the ending of the word. | \bge | geeks |
get | |||
\B | It is the opposite of the \b i.e. the string should not start or end with the given regex. | \Bge | together |
forge | |||
\d | Matches any decimal digit, this is equivalent to the set class [0-9] | \d | 123 |
gee1 | |||
\D | Matches any non-digit character, this is equivalent to the set class [^0-9] | \D | geeks |
geek1 | |||
\s | Matches any whitespace character. | \s | gee ks |
a bc a | |||
\S | Matches any non-whitespace character | \S | a bd |
abcd | |||
\w | Matches any alphanumeric character, this is equivalent to the class [a-zA-Z0-9_]. | \w | 123 |
geeKs4 | |||
\W | Matches any non-alphanumeric character. | \W | >$ |
gee<> | |||
\Z | Matches if the string ends with the given regex | ab\Z | abcdab |
abababab | |||
A Set is a set of characters enclosed in '[]' brackets. Sets are used to match a single character in the set of characters specified between brackets. Below is the list of Sets:
| Set | Description |
|---|---|
| \{n,\} | Quantifies the preceding character or group and matches at least n occurrences. |
| * | Quantifies the preceding character or group and matches zero or more occurrences. |
| [0123] | Matches the specified digits (0, 1, 2, or 3) |
| [^arn] | matches for any character EXCEPT a, r, and n |
| \d | Matches any digit (0-9). |
| [0-5][0-9] | matches for any two-digit numbers from 00 and 59 |
| \w | Matches any alphanumeric character (a-z, A-Z, 0-9, or _). |
| [a-n] | Matches any lower case alphabet between a and n. |
| \D | Matches any non-digit character. |
| [arn] | matches where one of the specified characters (a, r, or n) are present |
| [a-zA-Z] | matches any character between a and z, lower case OR upper case |
| [0-9] | matches any digit between 0 and 9 |
A Match object contains all the information about the search and the result and if there is no match found then None will be returned. Let's see some of the commonly used methods and attributes of the match object.
match.re attribute returns the regular expression passed and match.string attribute returns the string passed.
Example:
The code searches for the letter "G" at a word boundary in the string "Welcome to GeeksForGeeks" and prints the regular expression pattern (res.re) and the original string (res.string).
re.compile('\\bG')
Welcome to GeeksForGeeks
Example: Getting index of matched object
The code searches for substring "Gee" at a word boundary in string "Welcome to GeeksForGeeks" and prints start index of the match (res.start()), end index of the match (res.end()) and span of the match (res.span()).
11 14 (11, 14)
group() method returns the part of the string for which the patterns match. See the below example for a better understanding.
Example: Getting matched substring
The code searches for a sequence of two non-digit characters followed by a space and the letter 't' in the string "Welcome to GeeksForGeeks" and prints the matched text using res.group().
me t
In the above example, our pattern specifies for the string that contains at least 2 characters which are followed by a space, and that space is followed by a t.
Let's understand some of the basic regular expressions. They are as follows:
Character classes allow matching any one character from a specified set. They are enclosed in square brackets [].
['Geeks', 'Geeks', 'geeks']
In RegEx, a range allows matching characters or digits within a span using - inside []. For example, [0-9] matches digits, [A-Z] matches uppercase letters.
Range <re.Match object; span=(0, 1), match='x'>
Negation in a character class is specified by placing a ^ at the beginning of the brackets, meaning match anything except those characters.
Syntax:
[^a-z]
Example:
None None
Shortcuts are shorthand representations for common character classes. Let's discuss some of the shortcuts provided by the regular expression engine.
Geeks: <_sre.SRE_Match object; span=(0, 5), match='Geeks'> GeeksforGeeks: None
The ^ character chooses the beginning of a string and the $ character chooses the end of a string.
Beg. of String: None Beg. of String: <_sre.SRE_Match object; span=(0, 4), match='Geek'> End of String: <_sre.SRE_Match object; span=(31, 36), match='Geeks'>
The . character represents any single character outside a bracketed character class.
Any Character <_sre.SRE_Match object; span=(0, 6), match='python'>
Regular expression engine allows you to specify optional characters using the ? character. It allows a character or character class either to present once or else not to occur. Let's consider the example of a word with an alternative spelling - color or colour.
Color <_sre.SRE_Match object; span=(0, 5), match='color'> Colour <_sre.SRE_Match object; span=(0, 6), match='colour'>
Repetition enables you to repeat the same character or character class. Consider an example of a date that consists of day, month, and year. Let's use a regular expression to identify the date (mm-dd-yyyy).
Date{mm-dd-yyyy}: <_sre.SRE_Match object; span=(0, 10), match='18-08-2020'>Here, the regular expression engine checks for two consecutive digits. Upon finding the match, it moves to the hyphen character. After then, it checks the next two consecutive digits and the process is repeated.
Let's discuss three other regular expressions under repetition.
The repetition range is useful when you have to accept one or more formats. Consider a scenario where both three digits, as well as four digits, are accepted. Let's have a look at the regular expression.
Three Digit: <_sre.SRE_Match object; span=(0, 3), match='189'> Four Digit: <_sre.SRE_Match object; span=(0, 4), match='2145'>
There are scenarios where there is no limit for a character repetition. In such scenarios, you can set the upper limit as infinitive. A common example is matching street addresses. Let's have a look
<_sre.SRE_Match object; span=(0, 1), match='5'>
Shorthand characters allow you to use + character to specify one or more ({1,}) and * character to specify zero or more ({0,}.
<_sre.SRE_Match object; span=(0, 1), match='5'>
Grouping is the process of separating an expression into groups by using parentheses, and it allows you to fetch each individual matching group.
<_sre.SRE_Match object; span=(0, 10), match='26-08-2020'>
Let's see some of its functionality.
The re module allows you to return the entire match using the group() method
26-08-2020
You can use groups() method to return a tuple that holds individual matched groups
('26', '08', '2020')Upon passing the index to a group method, you can retrieve just a single group.
2020
The re module allows you to name your groups. Let's look into the syntax.
08
We have seen how regular expression provides a tuple of individual groups. Not only tuple, but it can also provide individual match as a dictionary in which the name of each group acts as the dictionary key.
{'dd': '26', 'mm': '08', 'yyyy': '2020'}In the case of a negated character class, it won't match if a character is not present to check against the negated character. We can overcome this case by using lookahead; it accepts or rejects a match based on the presence or absence of content.
negation: None lookahead: <_sre.SRE_Match object; span=(5, 6), match='n'>
Lookahead can also disqualify the match if it is not followed by a particular character. This process is called a positive lookahead, and can be achieved by simply replacing ! character with = character.
positive lookahead <_sre.SRE_Match object; span=(5, 6), match='n'>
The regular expression can replace the string and returns the replaced one using the re.sub method. It is useful when you want to avoid characters such as /, -, ., etc. before storing it to a database. It takes three arguments:
Let's have a look at the below code that replaces - character from a credit card number.
1111222233334444
Related Article: