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
🌐
Note.nkmk.me
note.nkmk.me › home › python
Extract a Substring from a String in Python (Position, Regex) | note.nkmk.me
April 29, 2025 - You can extract a substring within the range start <= x < stop using the syntax [start:stop]. If start is omitted, slicing begins from the start of the string.
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
Python Question - how do I extract a part of a string - Geographic Information Systems Stack Exchange
I'm building a tool in python and for that I have a question: I have a string such as "Denver.dwg Group Layer\Denver.dwg Annotation". How do I assign to a variable (for later print) only the firs... More on gis.stackexchange.com
🌐 gis.stackexchange.com
December 30, 2010
python - How to extract a part of a string - Stack Overflow
I have this string: -1007.88670550662*p**(-1.0) + 67293.8347365694*p**(-0.416543501823503) but actually I have a lot of string like this: a*p**(-1.0) + b*p**(c) where a,b and c are double. And I More on stackoverflow.com
🌐 stackoverflow.com
regex - How do I extract a certain part of a string in Python? - Stack Overflow
I was wondering how I would extract a certain part of a string in Python. So, let's say I have a list. (EXAMPLE) 1 || awdawd@awdawd.com || awlkdjawldkjalwdkda 2 || aawdawd@awd.com || awdadwawdawd... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Sentry
sentry.io › sentry answers › python › extract a substring from a string in python
Extract a substring from a string in Python
2 weeks ago - Extract substrings from Python strings using slice notation with [start:end] indexes, or use re.search() with regex patterns for matching specific formats
🌐
EyeHunts
tutorial.eyehunts.com › home › python extract part of a string | example code
Python extract part of a string | Example code - EyeHunts
October 20, 2021 - Doing slicing will extract part of a string in Python. Use square-bracket syntax with the starting position of the piece we want, but also...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-substring-a-string-in-python
How to Substring a String in Python - GeeksforGeeks
July 23, 2025 - In this example, we are trying to extract the starting word from the string.we used string slicing to extract the substring "Geeks" from the beginning of the string. The slice notation str[:5] starts at index 0 (the first character) and goes up to, but does not include, index 5, resulting in "Geeks". ... In this example we are trying to extract the last portion of the string.we used string slicing to extract the substring "best!".
🌐
freeCodeCamp
freecodecamp.org › news › how-to-substring-a-string-in-python
How to Substring a String in Python
January 3, 2020 - Python offers many ways to substring a string. This is often called "slicing". Here is the syntax: string[start:end:step] Where, start: The starting index of the substring. The character at this index is included in the substring. If start is not in...
🌐
Delft Stack
delftstack.com › home › howto › python › extract substring from a string in python
How to Extract Substring From a String in Python | Delft Stack
February 2, 2024 - -1 can be used to define the last index in Python. [-6 : -1] -> Returns a substring starting from the sixth index from the end till the second last index. Instead of mentioning the indexes inside the brackets, we can use the slice() constructor to create a slice object to slice a string or any other sequence such as a list or tuple.
🌐
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!

Find elsewhere
🌐
iO Flood
ioflood.com › blog › python-substring-quick-reference
Python Substring Quick Reference
January 31, 2024 - Python’s re module supports regular expressions, providing a robust platform for complex string manipulations. When it comes to substring extraction, regular expressions come into their own when you want to extract a substring that matches a specific pattern. For instance, you may need to extract all email addresses from a text or all dates in a particular format. Let’s look at an example of using regular expressions to extract substrings in Python:
🌐
Quora
quora.com › How-do-you-extract-a-part-of-a-string-in-Python
How to extract a part of a string in Python - Quora
Answer (1 of 4): The part of a string can be extracted by indexing and slicing. Using indexing you can extract only one character by their desired index number. Ex: str = “Python is an easy programming language" print(str[0]) It will print the ‘p' of python. Like wise, using slicing you can...
🌐
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
🌐
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 - How to get substring of a string in Python? There are several methods you can use to get specific portions of a string, from simple slicing and string
🌐
Medium
medium.com › @blogshub4 › extracting-substrings-from-strings-in-python-f714960b8c19
Extracting Substrings from Strings in Python | by Blogshub | Medium
December 24, 2024 - The slice operator string[start:end:step] allows you to extract a portion of a string. Here’s how its components work: start: The index where the substring starts (inclusive). end: The index where the substring ends (exclusive). step: Specifies ...
🌐
Vultr
docs.vultr.com › python › examples › get-a-substring-of-a-string
Python Program to Get a Substring of a String | Vultr Docs
December 25, 2024 - Extract parts of strings that match specific criteria. ... import re full_text = "Contact us at: info@example.com" match = re.search(r"[\w\.-]+@[\w\.-]+", full_text) if match: print(match.group(0)) Explain Code · This code identifies email addresses in the string and extracts info@example.com. Regular expressions are potent for pattern matching and substring extraction in data validation tasks. Extracting substrings is a routine task in Python programming, crucial in various domains such as text preprocessing, data validation, and pattern recognition.
🌐
Dot Net Perls
dotnetperls.com › substring-python
Python - Substring Examples - Dot Net Perls
September 20, 2024 - Result When we use first_words, ... Buck Mulligan came from the stairhead." result = first_words(test, ... In Python we extract parts of strings with slices....
Top answer
1 of 6
3

If you're allergic to REs, you could use pyparsing:

>>> import pyparsing as p
>>> ope, clo, com = map(p.Suppress, '(),')
>>> w = p.Word(p.alphas)
>>> s = ope + w + com + w + com + ope + p.delimitedList(w) + clo + clo
>>> x = '(xx,yyy,(aa,bb,cc))'
>>> list(s.parseString(x))
['xx', 'yyy', 'aa', 'bb', 'cc']

pyparsing also makes it easy to control the exact form of results (e.g. by grouping the last 3 items into their own sublist), if you want. But I think the nicest aspect is how natural (depending on how much space you want to devote to it) you can make the "grammar specification" read: an open paren, a word, a comma, a word, a comma, an open paren, a delimited list of words, two closed parentheses (if you find the assignment to s above not so easy to read, I guess it's my fault for not choosing longer identifiers;-).

2 of 6
3

If your parenthesis nesting can be arbitrarily deep, then regexen won't do, you'll need a state machine or a parser. Pyparsing supports recursive grammars using forward-declaration class Forward:

from pyparsing import *

LPAR,RPAR,COMMA = map(Suppress,"(),")
nestedParens = Forward()
listword = Word(alphas) | '...'
nestedParens << Group(LPAR + delimitedList(listword | nestedParens) + RPAR)

text = "(xx,yyy,(aa,bb,...))"
results = nestedParens.parseString(text).asList()
print results

text = "(xx,yyy,(aa,bb,(dd,ee),ff,...))"
results = nestedParens.parseString(text).asList()
print results

Prints:

[['xx', 'yyy', ['aa', 'bb', '...']]]
[['xx', 'yyy', ['aa', 'bb', ['dd', 'ee'], 'ff', '...']]]
🌐
ReqBin
reqbin.com › code › python › h73zla88 › python-substring-example
How do I get a substring from a string in Python?
December 25, 2022 - To get a substring from a string in Python, you can use the slicing operator string[start:end:step]. The slice operator returns the part of a string between the "start" and "end" indices.