To extract a string between delimiters in Python, you can use regular expressions (regex). The re
module in Python provides functions to work with regular expressions.
You can use regex
import re
s = re.findall('\[(.*?)\]', str)
For example, in the string "Hello [World]! How [are] you doing?"
, if the delimiters are set as [
and ]
, the extracted substrings would be "World"
and "are"
respectively.
import re
text = "Hello [World]! How [are] you doing?"
result = re.findall('\[(.*?)\]', text)
print(result) # Output: ['World', 'are']
Python extracts string between delimiters example
Here’s an example of how to extract strings between delimiters using the regular expression method that I mentioned earlier:
def extract_str(text, start_delimiter, end_delimiter):
start_index = text.find(start_delimiter)
end_index = text.find(end_delimiter, start_index + len(start_delimiter))
if start_index != -1 and end_index != -1:
return text[start_index + len(start_delimiter):end_index]
else:
return None
# Example usage:
text = "This is a [sample] text with [multiple] delimiters."
start_delimiter = "["
end_delimiter = "]"
result = extract_str(text, start_delimiter, end_delimiter)
print(result)
Output:
Both methods will yield the same result. The find()
method is used to locate the positions of the start_delimiter
and end_delimiter
in the text
. If both delimiters are found, the desired substring is extracted using string slicing.
Note: these methods will return the first occurrence of the substring between the delimiters if there are multiple occurrences. If there are no occurrences of the delimiters, they will return None
.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.