[1116] Python Regular Expression (re)
ref: Python RegEx - geeksforgeeks
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.
Regex Module in Python
Python has a built-in module named “re” that is used for regular expressions in Python. We can import this module by using the import statement.
RegEx Functions
re module contains many functions that help us to search a string for a match.
Let’s see various functions provided by this module to work with regex in Python.
Function | Description |
---|---|
re.findall() | finds and returns all matching occurrences in a list |
re.search() | Searches for first occurrence of character or pattern |
Let’s see the working of these RegEx functions with definition and examples:
1. re.findall()
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.
Finding all occurrences of a pattern
This code uses a regular expression (\d+
) to find all the sequences of one or more digits in the given string. It searches for numeric values and stores them in a list. In this example, it finds and prints the numbers “123456789” and “987654321” from the input string.
import re string = """Hello my Number is 123456789 and my friend's number is 987654321""" regex = '\d+' match = re.findall(regex, string) print(match)
['123456789', '987654321']
2. re.search()
This method either returns None (if the pattern doesn’t match), or a re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Example: Searching for an occurrence of the pattern
This code uses a regular expression to search for a pattern in the given string. If a match is found, it extracts and prints the matched portions of the string.
In this specific example, it searches for a pattern that consists of a month (letters) followed by a day (digits) in the input string “I was born on June 24”. If a match is found, it prints the full match, the month, and the day.
import re regex = r"([a-zA-Z]+) (\d+)" match = re.search(regex, "I was born on June 24") if match != None: print ("Match at index %s, %s" % (match.start(), match.end())) print ("Full match: %s" % (match.group(0))) print ("Month: %s" % (match.group(1))) print ("Day: %s" % (match.group(2))) else: print ("The regex pattern does not match.")
Meta-characters
Metacharacters are the characters with special meaning.
To understand the RE analogy, Metacharacters are useful and important. They will be used in functions of module re. Below is the list of metacharacters.
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:
1. \ – Backslash
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.
import re s = 'geeks.forgeeks' # without using \ match = re.search(r'.', s) print(match) # using \ match = re.search(r'\.', s) print(match)
2. [] – Square Brackets
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,
- [0-3] is sample as [0123]
- [a-c] is same as [abc]
We can also invert the character class using the caret(^) symbol. For example,
- [^0-3] means any character except 0, 1, 2, or 3
- [^a-c] means any character except a, b, or c
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’.
import re string = "The quick brown fox jumps over the lazy dog" pattern = "[a-m]" result = re.findall(pattern, string) print(result)
3. ^ – Caret
Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given character(s) or not. For example –
- ^g will check if the string starts with g such as geeks, globe, girl, g, etc.
- ^ge will check if the string starts with ge such as geeks, geeksforgeeks, etc.
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”.
import re regex = r'^The' strings = ['The quick brown fox', 'The lazy dog', 'A quick brown fox'] for string in strings: if re.match(regex, string): print(f'Matched: {string}') else: print(f'Not matched: {string}')
4. $ – Dollar
Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given character(s) or not. For example-
- s$ will check for the string that ends with a such as geeks, ends, s, etc.
- ks$ will check for the string that ends with ks such as geeks, geeksforgeeks, ks, etc.
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”.
import re string = "Hello World!" pattern = r"World!$" match = re.search(pattern, string) if match: print("Match found!") else: print("Match not found.")
5. . – Dot
Dot(.) symbol matches only a single character except for the newline character (\n). For example –
- a.b will check for the string that contains any character at the place of the dot such as acb, acbd, abbb, etc
- .. will check if the string contains at least 2 characters
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”.
import re string = "The quick brown fox jumps over the lazy dog." pattern = r"brown.fox" match = re.search(pattern, string) if match: print("Match found!") else: print("Match not found.")
Match found!
6. | – Or
Or symbol works as the or operator meaning it checks whether the pattern before or after the or symbol is present in the string or not. For example –
- a|b will match any string that contains a or b such as acd, bcd, abcd, etc.
7. ? – Question Mark
The question mark (?) is a quantifier in regular expressions that 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.
8.* – Star
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.
9. + – Plus
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.
10. {m, n} – Braces
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.
11. (<regex>) – Group
Group symbol is used to group sub-patterns. For example –
- (a|b)cd will match for strings like acd, abcd, gacd, etc.
Special Sequences
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.
List of special sequences
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 |
Sets for character matching
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 |
Match Object
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.
1. Getting the string and the regex
match.re attribute returns the regular expression passed and match.string attribute returns the string passed.
Example: Getting the string and the regex of the matched object
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
).
import re s = "Welcome to GeeksForGeeks" res = re.search(r"\bG", s) print(res.re) print(res.string)
re.compile('\\bG') Welcome to GeeksForGeeks
2. Getting index of matched object
- start() method returns the starting index of the matched substring
- end() method returns the ending index of the matched substring
- span() method returns a tuple containing the starting and the ending index of the matched substring
Example: Getting index of matched object
The code searches for the substring “Gee” at a word boundary in the string “Welcome to GeeksForGeeks” and prints the start index of the match (res.start()
), the end index of the match (res.end()
), and the span of the match (res.span()
).
import re s = "Welcome to GeeksForGeeks" res = re.search(r"\bGee", s) print(res.start()) print(res.end()) print(res.span())
3. Getting matched substring
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()
.
import re s = "Welcome to GeeksForGeeks" res = re.search(r"\D{2} t", s) print(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.
Related Article :
https://www.geeksforgeeks.org/regular-expressions-python-set-1-search-match-find/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2024-03-05 [982] Print and save a JSON file with indentation in Python
2014-03-05 【139】论文查重修改技巧大全