Python Extract Substring Using Regex
Last Updated :
23 Feb, 2024
Python provides a powerful and flexible module called re
for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we’ll explore four simple and commonly used methods to extract substrings using regex in Python.
Python Extract Substring Using Regex
Below, are the methods of Python Extract Substring Using Regex in Python.
Python Extract Substring Using Regex Using re.search()
In this example, below Python code utilizes `re.search()` to find the substring “Python” in the string “I love Python.” If a match is found, it prints the matched substring using `match.group()`, demonstrating a basic example of substring extraction with regular expressions.
Python3
import re
string = "I love Python"
pattern = "Python"
match = re.search(pattern, string)
if match:
print (match.group())
|
Python Extract Substring Using Regex Using re.findall() Method
In this example, below Python code uses `re.findall()` to find all occurrences of the case-sensitive pattern “the” in the given string “The quick brown fox jumps over the lazy dog,” and it prints the list of matching substrings.
Python3
import re
string = "The quick brown fox jumps over the lazy dog"
pattern = "the"
matches = re.findall(pattern, string)
print (matches)
|
Python Extract Substring Using Regex Using re.split() Method
In this example, below Python code uses `re.split()` with the pattern “,” to split the string “1,2,3,4,5” into a list of substrings based on the commas. The result, when printed using `print(numbers)`, is a list containing individual numbers: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’].
Python3
import re
string = "1,2,3,4,5"
pattern = ","
numbers = re.split(pattern, string)
print (numbers)
|
Output
['1', '2', '3', '4', '5']
Share your thoughts in the comments
Please Login to comment...