If you're new to REG(gular) EX(pressions) you learn about them at Python Docs. Or, if you want a gentler introduction, you can check out the HOWTO. They use Perl-style syntax.

Regex

The expression that you need is .*?\[(.*)\].*. The group that you want will be \1.
- .*?: . matches any character but a newline. * is a meta-character and means Repeat this 0 or more times. ? makes the * non-greedy, i.e., . will match up as few chars as possible before hitting a '['.
- \[: \ escapes special meta-characters, which in this case, is [. If we didn't do that, [ would do something very weird instead.
- (.*): Parenthesis 'groups' whatever is inside it and you can later retrieve the groups by their numeric IDs or names (if they're given one).
- \].*: You should know enough by now to know what this means.

Implementation

First, import the re module -- it's not a built-in -- to where-ever you want to use the expression.

Then, use re.search(regex_pattern, string_to_be_tested) to search for the pattern in the string to be tested. This will return a MatchObject which you can store to a temporary variable. You should then call it's group() method and pass 1 as an argument (to see the 'Group 1' we captured using parenthesis earlier). I should now look like:

>>> import re
>>> pat = r'.*?\[(.*)].*'             #See Note at the bottom of the answer
>>> s = "foobar['infoNeededHere']ddd"
>>> match = re.search(pat, s)
>>> match.group(1)
"'infoNeededHere'"

An Alternative

You can also use findall() to find all the non-overlapping matches by modifying the regex to (?>=\[).+?(?=\]).
- (?<=\[): (?<=) is called a look-behind assertion and checks for an expression preceding the actual match.
- .+?: + is just like * except that it matches one or more repititions. It is made non-greedy by ?.
- (?=\]): (?=) is a look-ahead assertion and checks for an expression following the match w/o capturing it.
Your code should now look like:

>>> import re
>>> pat = r'(?<=\[).+?(?=\])'  #See Note at the bottom of the answer
>>> s = "foobar['infoNeededHere']ddd[andHere] [andOverHereToo[]"
>>> re.findall(pat, s)
["'infoNeededHere'", 'andHere', 'andOverHereToo['] 

Note: Always use raw Python strings by adding an 'r' before the string (E.g.: r'blah blah blah').

10x for reading! I wrote this answer when there were no accepted ones yet, but by the time I finished it, 2 ore came up and one got accepted. :( x<

Answer from Yatharth Agarwal on Stack Overflow
🌐
H2K Infosys
h2kinfosys.com › home › python tutorials › how to extract a string between two characters in python
How to Extract a String Between Two Characters in Python | H2K Infosys Blog
December 18, 2025 - Regular expressions provide a more powerful and flexible way to search and extract patterns from strings. Python’s re module makes it easy to use regex for string extraction.
Top answer
1 of 3
74

If you're new to REG(gular) EX(pressions) you learn about them at Python Docs. Or, if you want a gentler introduction, you can check out the HOWTO. They use Perl-style syntax.

Regex

The expression that you need is .*?\[(.*)\].*. The group that you want will be \1.
- .*?: . matches any character but a newline. * is a meta-character and means Repeat this 0 or more times. ? makes the * non-greedy, i.e., . will match up as few chars as possible before hitting a '['.
- \[: \ escapes special meta-characters, which in this case, is [. If we didn't do that, [ would do something very weird instead.
- (.*): Parenthesis 'groups' whatever is inside it and you can later retrieve the groups by their numeric IDs or names (if they're given one).
- \].*: You should know enough by now to know what this means.

Implementation

First, import the re module -- it's not a built-in -- to where-ever you want to use the expression.

Then, use re.search(regex_pattern, string_to_be_tested) to search for the pattern in the string to be tested. This will return a MatchObject which you can store to a temporary variable. You should then call it's group() method and pass 1 as an argument (to see the 'Group 1' we captured using parenthesis earlier). I should now look like:

>>> import re
>>> pat = r'.*?\[(.*)].*'             #See Note at the bottom of the answer
>>> s = "foobar['infoNeededHere']ddd"
>>> match = re.search(pat, s)
>>> match.group(1)
"'infoNeededHere'"

An Alternative

You can also use findall() to find all the non-overlapping matches by modifying the regex to (?>=\[).+?(?=\]).
- (?<=\[): (?<=) is called a look-behind assertion and checks for an expression preceding the actual match.
- .+?: + is just like * except that it matches one or more repititions. It is made non-greedy by ?.
- (?=\]): (?=) is a look-ahead assertion and checks for an expression following the match w/o capturing it.
Your code should now look like:

>>> import re
>>> pat = r'(?<=\[).+?(?=\])'  #See Note at the bottom of the answer
>>> s = "foobar['infoNeededHere']ddd[andHere] [andOverHereToo[]"
>>> re.findall(pat, s)
["'infoNeededHere'", 'andHere', 'andOverHereToo['] 

Note: Always use raw Python strings by adding an 'r' before the string (E.g.: r'blah blah blah').

10x for reading! I wrote this answer when there were no accepted ones yet, but by the time I finished it, 2 ore came up and one got accepted. :( x<

2 of 3
27

^.*\['(.*)'\].*$ will match a line and capture what you want in a group.

You have to escape the [ and ] with \

The documentation at the rubular.com proof link will explain how the expression is formed.

Discussions

Python/Regex: Get all strings between any two characters - Stack Overflow
I have a use case that requires the identification of many different pieces of text between any two characters. For example, String between a single space and (: def test() would return test String More on stackoverflow.com
🌐 stackoverflow.com
February 16, 2018
python - Match text between two strings with regular expression - Stack Overflow
I would like to use a regular expression that matches any text between two strings: Part 1. Part 2. Part 3 then more text In this example, I would like to search for "Part 1" and "Part 3" and then... More on stackoverflow.com
🌐 stackoverflow.com
Python Regex Get String Between Two Substrings - Stack Overflow
First off, I know this may seem like a duplicate question, however, I could find no working solution to my problem. I have string that looks like the following: string = "api('randomkey123xyz987'... More on stackoverflow.com
🌐 stackoverflow.com
April 17, 2015
Return the String between two characters
that is a very ugly html. where are the opening divs? you could use regex import re data = '
Hey
Hey2' heys = re.findall('>(\w+)' and ' More on reddit.com
🌐 r/learnpython
20
2
July 21, 2022
🌐
pythoncodelab
pythoncodelab.com › home › python: get text between two strings, characters, or delimiters
Python: Get text between two strings, characters, or delimiters
January 14, 2026 - When we want to extract text which has a complex pattern, we can use regular expressions (regex). Python’s re module can be used to match patterns and extract text between two strings, characters and delimiters.
🌐
Vitoshacademy
vitoshacademy.com › python-find-all-substrings-between-two-character-pairs-with-regex
Python – Find All Substrings Between Two Character Pairs with RegEx – Useful code
December 21, 2021 - And as visible, the character pairs will be these – Joe and Banana. As the last time I had to do this, the trivial task took me some solid 5 minutes, now I have decided to invest another 10 in writing this article, so hopefully in the long run I will save a minute or 2. Long story short – this is the function: import re def find_between(s, first, last): try: regex = rf'{first}(.*?){last}' return re.findall(regex, s) except ValueError: return -1 s = "Joe Ivan Banana, George Joe J.
🌐
EyeHunts
tutorial.eyehunts.com › home › python extract substring between two characters | example code
Python extract substring between two characters | Example code
April 29, 2022 - You can do this with RegEx to extract substring between two characters in Python. You can use owe logic for it like index() function with for-loop or slice notation. A simple example code gets text between two char in Python.
🌐
Regex Tester
regextester.com › 96872
Extract String Between Two STRINGS - Regex Tester/Debugger
Regex Tester is a tool to learn, build, & test Regular Expressions (RegEx / RegExp). Results update in real-time as you type. Roll over a match or expression for details. Save & share expressions with others. Explore the Library for help & examples. Undo & Redo with {{getCtrlKey()}}-Z / Y. Search for & rate Community patterns. ... extended (x) extra (X) single line (s) unicode (u) Ungreedy (U) Anchored (A) dup subpattern names(J) ... Url checker with or without http:// or https:// Match string not containing string Check if a string only contains numbers Only letters and numbers Match elements
Find elsewhere
🌐
Java2Blog
java2blog.com › home › python › python string › get string between two characters in python
Get String Between Two Characters in Python - Java2Blog
November 28, 2022 - To conclude, we discussed several methods in this article to get string between two characters in Python. In the first method, we used the string-slicing technique. In this method, we find the positions of the two characters and extract the required string between them using this technique. The next method discusses the use of the re library for the same. This method uses regular expressions to find the required substring using a regex pattern with the re.search() function.
🌐
CodeVsColor
codevscolor.com › python program to get the string between two substrings - codevscolor
Python program to get the string between two substrings - CodeVsColor
September 10, 2021 - We need the string just before this character. The print statement is using string slicing to find the required string. It starts a start_index and ends at end_index - 1. Regular expression or regex is the most popular way to search for a substring that matches a pattern. In our case, the pattern can be any string that starts and ends with the provided strings. Python provides re module to work with regex.
🌐
stataiml
stataiml.com › posts › 32_extract_string_between_python
How to Extract String Between Two Characters or Strings in Python - stataiml
May 3, 2024 - ... If you want to extract a string between two strings such as XYZ and ABC from the input string, you can use the search() function. import re m = re.search('XYZ(.*)ABC', input_string) # get extracted string ext_string = m.group(1) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-string-between-two-substrings
Python – Extract string between two substrings | GeeksforGeeks
January 18, 2025 - A substring is any contiguous sequence of characters within the string. We'll discuss various methods to extract this substring from a given string by using a simple approach. Using List Comprehension :List comprehension offers a concise way to create lists by applying an expression to each element ... 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.
🌐
Tutor Python
tutorpython.com › python-to-find-a-string-between-two-strings
3 Ways in Python to find a string between two strings - Tutor Python
April 25, 2024 - Regular expressions (regex) are a powerful tool for manipulating text. They provide a flexible way to search and match string patterns within larger text strings. In Python, the re module provides support for regular expressions and is part of the standard library.
🌐
regex101
regex101.com › library › T7scY8
regex101: Extract String Between Two Strings
Using the [0-9a-f] character set. ... Oltre a supportare le omocodie controlla in modo restrittivo il carattere relativo al mese di nascita ... To get a variable name from a source code: The variable name is before the '=' (equal sign) This ...
🌐
Reddit
reddit.com › r/learnpython › return the string between two characters
r/learnpython on Reddit: Return the String between two characters
July 21, 2022 -

I am trying to return the string between two characters.

entry_list = []
data = '<br>Hey</div> <br>Hey2</div>'
for i in data:
    a,b = data.split('<br>') 
    c,d = b.split(</div>)
    entry_list.append(c)
print('\n'.join(entry_list))

This code does not run.

How would I search a Python string, and return the value between <br> and </div> multiple times.

🌐
GitHub
gist.github.com › vxhviet › 6533c0be8ccc310edb4b10d90d0d383b
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · GitHub
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Raw · regex.md · Source: StackOverflow · Question: Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Answer: Easy done: (?<=\[)(.*?)(?=\]) Technically that's using lookaheads and look behinds.