Using regular expressions - documentation for further reference

import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

or:

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234
Answer from eumiro on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-extract-substring-using-regex
Python Extract Substring Using Regex - GeeksforGeeks
July 23, 2025 - In this article, we'll explore four simple and commonly used methods to extract substrings using regex in Python.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Extract a Substring from a String in Python (Position, Regex) | note.nkmk.me
April 29, 2025 - In Python, you can use regular expressions (regex) with the re module of the standard library. ... Use re.search() to extract the first substring that matches a regex pattern.
Discussions

The simplest way to extract a substring from a string
I personally would either use string slicing or a regex. For example, the slicing version would probably look something like substring = string[string.find("(") + 1:string.find(")")] and the regex you would use would probably look something like this: re.search(r'\((.*?)\)', string).group(1) More on reddit.com
๐ŸŒ r/learnpython
5
1
May 27, 2021
how to extract only names in string by using regex
It seems like the pattern your searching for is "title, space, word". You can use 'Ms. ', 'Mrs. ', and 'Mr. ' for the title and space, but there are a ton of titles in the real world (stuff like 'Dr. ', 'Prof. ', 'Captain ', 'Reverend ', etc.) So one such regex string could be: r'(Ms. |Mrs. |Mr. )([A-Za-z]+)' More on reddit.com
๐ŸŒ r/learnpython
6
0
March 22, 2023
python - Using regex to extract substrings - Stack Overflow
I have a string: s = r'"url" : "a", "meta": "b", "url" : "c"' What I want is to capture the substring url: ... up to the ,, so the expec... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: best way to find and extract substring from a string?
Your post is kind of messed up because you didn't format your example properly as a code block. But based on the way your Markdown formatting came out, I'm guessing that the three strings you're looking for are on lines by themselves that start with a # symbol. In that case you could just do something along the lines of: lines = string.split('\n') heading_lines = [l for l in lines if l.startswith('#')] title, description, results = [l.strip('#').strip() for l in heading_lines[:3]] More on reddit.com
๐ŸŒ r/learnprogramming
10
6
October 9, 2024
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ extract a substring from a string in python
Extract a substring from a string in Python
1 week ago - Extract substrings from Python strings using slice notation with [start:end] indexes, or use re.search() with regex patterns for matching specific formats
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ python โ€บ h73zla88 โ€บ python-substring-example
How do I get a substring from a string in Python?
December 25, 2022 - Regular expressions are a powerful string manipulation tool in Python that is natively supported in Python. To extract a substring from a string using regular expressions, you must first import the "re" module into your code.
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python regex extract substring | example code
Python regex extract substring | Example code - EyeHunts
August 24, 2021 - Using a "re" module findall() function with regex can extract a substring from a given string in Python. Call re.findall(r"pattern (.*)"...
๐ŸŒ
Linux Hint
linuxhint.com โ€บ extract-substring-regex-python
Linux Hint โ€“ Linux Hint
March 20, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ datadaft
Python Regex: How Find a Substring in a String - YouTube
โ†“ Code Available Below! โ†“ This video shows how to find and extract substrings within python strings using the regular expressions package. Locating and extra...
Published ย  September 30, 2020
Views ย  451
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ get substring of a string in python
Get substring of a string in Python - Spark By {Examples}
May 31, 2024 - Pythonโ€™s re module provides support for regular expressions. The module provides various methods for searching for and extracting substrings based on regular expression patterns. See the following example that uses Regular expression to get a substring from a string: # Import re module import re # Using regex to extract the first word match = re.search(r"\b\w+\b", s) substring = match.group(0) print(substring) # Extracts "SparkByExamples" # Using regex to extract the word "Good" match = re.search(r"\bGood\b", s) substring = match.group(0) print(substring) # Extracts "Good" # Using regex to replace "Good" with "Great" substring = re.sub(r"\bGood\b", "Great", s) print(substring) # Replaces "Good" with "Great"
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ the simplest way to extract a substring from a string
r/learnpython on Reddit: The simplest way to extract a substring from a string
May 27, 2021 -

Hello,

I'm learning python from scratch, and I am trying to figure out how to "extract" a substring from a string. So, for instance, let's say I want to extract the word within the parenthesis for each of these three strings.

'xx(hi)xx' 'abc(there)xyz' 'xx(c)xx'

I know I could use slicing, but this would involve three operations, I think. I'm wondering if there's a sort of pattern I can leverage. How do you guys approach this kind of problem?

Thank you in advance for your help. It is most appreciated!

๐ŸŒ
Medium
medium.com โ€บ quantrium-tech โ€บ extracting-words-from-a-string-in-python-using-regex-dac4b385c1b8
Extracting Words from a string in Python using RegEx
October 6, 2020 - This is one of the ways in which you can use the () operator to extract particular patterns that we are interested in, which occur along with some other pattern that we are not interested in capturing, like we want to ignore the '@' symbol in our case. To understand all the fundamental components of regex in Python, the best way to do so is by heading to the official documentation of Python 3.8 RegEx here:
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-extract-a-substring-from-inside-a-string-in-python
How to extract a substring from inside a string in Python?
May 20, 2025 - The re module provides powerful pattern matching capabilities for complex substring extraction using regular expressions.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to extract only names in string by using regex
r/learnpython on Reddit: how to extract only names in string by using regex
March 22, 2023 -
import re
text = "433 - 675 - 8765 - 322 - 533 - 7665 Mr. Roy Mr. David Mrs. Pooja Ms. Sharma Mr. T "
res=re.findall("",text)
print(res)

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-extract-string-between-two-substrings
Python - Extract string between two substrings - GeeksforGeeks
January 15, 2026 - Using the re module regular expressions allow flexible and efficient pattern matching to extract substrings between specified delimiters. ... # Import the regular expression module import re # Define the input string s = "Hello [world]!" # Define ...
๐ŸŒ
Python for Everybody
py4e.com โ€บ html3 โ€บ 11-regex
PY4E - Python for Everybody
In the example above, using .+?@ ... non-greedy quantifiers. If we want to extract data from a string in Python we can use the findall() method to extract all of the substrings which match ......
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ substring-of-string-python
How to Get a Substring of a String in Python | LearnPython.com
April 26, 2022 - However, this is not optimal for extracting individual words from a string since it requires knowing the indexes in advance. Another option to get a substring of the string is to break it into words, which can be done with the string.split() method.
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ py4e-int โ€บ regex โ€บ extractingdata.html
12.3. Extracting Data Using Regular Expressions โ€” Python for Everybody - Interactive
12.15 Group Work: More Regular Expressions (Regex) If we want to extract data from a string in Python we can use the findall() method to extract all of the substrings which match a regular expression. Letโ€™s use the example of wanting to extract anything that looks like an email address from ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to use regex to extract substring between given markers?
r/learnpython on Reddit: How to use regex to extract substring between given markers?
May 16, 2020 -

I find regex especially intimidating, so any help here is appreciated. I need to extract a substring of variable length from a longer string. The substring always occurs between two constant patterns, and I don't know how to put that into regex. I'll give an example below:

Below is the big string I need to parse. All I need to extract is "DSC_0026.NEF".

FileMetadata(name='DSC_0026.NEF', id='id:1X3HG93XOX8AAAAAAAMhEA', client_modified=datetime.datetime(2020, 3, 18, 16, 38, 31), server_modified=datetime.datetime(2020, 4, 2, 18, 33, 21), rev='015a253090fa3350000000199c64dd0', size=8015265, path_lower='/02_dunesburyproductimages/2020/03 march/dsc_0026.nef', path_display='/02_DunesburyProductImages/2020/03 March/DSC_0026.NEF', parent_shared_folder_id='6874877392', media_info=None, symlink_info=None, sharing_info=FileSharingInfo(read_only=False, parent_shared_folder_id='6874977392', modified_by='dbid:AAB6MO1TmreSuq_O661AXKiKNAVwJn4N6_4'), is_downloadable=True, export_info=None, property_groups=None, has_explicit_shared_members=None, content_hash='96595111b66a2d47bf6086f74d7c01c2a1738b096737dx9ac0c63ac7becee2c3', file_lock_info=None), 

What I think would work is somehow telling the regex to return everything between name=' and ', id, but I have no idea how to do that. I'm not looking for anyone to write code for me; I need to learn regex anyway, so I'd prefer a resource to learn how to do this. The more "dumbed down" it is, the better.

Thanks for any help, I really appreciate it :)

Top answer
1 of 3
3
As with most things there are a few ways to do it, but I'll use re.search (re.findall and re.finditer are good for finding multiple values). The simplest starting point would be finding the position of a single-quote (we need to use backslashes since they're special characters in regex): pattern = "\'" match = re.search(pattern, text) if match is not None: print(f"Start: {match.start()}") Now let's try finding the position of a single-quote that is preceded by "name=". We can use a "look-behind" for this, which is a special section in parentheses containing "?<=". It means whatever you're trying to match has to come after some pattern. The equals symbol between "name" and the single-quote also requires a backslash: pattern = "(?<=name\=)\'" With this in place, it'll find the starting point of "name=" specifically rather than the first occurrence, so if the order of the values in your text changes, you're still good. Next you want to find the contents of the name value. We want zero-or-more characters of any kind minus the single-quote. Use square brackets to indicate a set, a caret to indicate "except", and an asterisk meaning zero-to-many: pattern = "(?<=name\=)\'[^\']*" match = re.search(pattern, text) if match is not None: print(f"Match: {match}") If you print the match out here, you'll see we're almost there. It'll show the start and end positions of the match, as well as the text which is almost correct, except it contains the starting single-quote. You can address that by moving the quote into the "look-behind" section: pattern = (?<=name\=\')[^\']*" match = re.search(pattern, text) if match is not None: name = match.group(0) There are a ton of resources out there but the main thing I find it takes is practice. I've been using regex intermittently for 20+ years but if I don't use it for more than a few months I still find myself re-learning parts.
2 of 3
2
Then don't use regex; use .index() to search for name=' and then to search for ', id=' and slice the bit between them: text = "FileMeta..." start = text.index("name='") end = text.index("', id=", start) text[start:end] You'll have to adjust for the length of "name='" a little.