import re
s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))
# returns 'iwantthis'
Answer from Nikolaus Gradwohl on Stack Overflow Top answer 1 of 16
526
import re
s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))
# returns 'iwantthis'
2 of 16
188
s = "123123STRINGabcabc"
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def find_between_r( s, first, last ):
try:
start = s.rindex( first ) + len( first )
end = s.rindex( last, start )
return s[start:end]
except ValueError:
return ""
print find_between( s, "123", "abc" )
print find_between_r( s, "123", "abc" )
gives:
123STRING
STRINGabc
I thought it should be noted - depending on what behavior you need, you can mix index and rindex calls or go with one of the above versions (it's equivalent of regex (.*) and (.*?) groups).
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 - You can split the string based on the characters. pythonCopy codetext = "Hello [world]!" result = text.split("[")[1].split("]")[0] print(result) # Output: world · Some languages or environments have libraries for text manipulation. javascript const text = "Hello [world]!"; const match = text.match(/\[(.*?)\]/); if (match) { console.log(match[1]); // Output: world } Manually loop through the string to extract content between characters.
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
Hey
Hey2' heys = re.findall('>(\w+)' and ' More on reddit.com
getting string between 2 characters in python - Stack Overflow
I need to get certain words out from a string in to a new format. For example, I call the function with the input: text2function('$sin (x)$ is an function of x') and I need to put them into a More on stackoverflow.com
Python coding : get string between two characters
I want to get a substring between two characters (/ and ?) from some url I have For example, I have : https://partners.doctolib.fr/vaccination-covid-19/rennes/centre-de-vaccination-covid-19-rennes-... More on github.com
Python-Get String Between Two Characters
You could replace these with an empty string. Then use re.split with either the '^' or '>' characters. You have to escape '^' because it has special meaning to a regular expression. Using the pipe character creates an or condition in a regular expression. Then that would give me results but they would have a lot of whitespace, so I would use a list comprehension to get rid of the extra whitespace and to omit any blank entries from the list. ... #!/usr/bin/env python ... More on gamedev.net
PythonForBeginners.com
pythonforbeginners.com › home › how to split a string between characters in python
How to Split a String Between Characters in Python - PythonForBeginners.com
August 17, 2021 - Slice objects take three parameters: start, stop and step. The first two parameters tell Python where to start and end the slice, while the step parameter describes the increment between each step. With a slice object we can get a substring between characters.
stataiml
stataiml.com › posts › 32_extract_string_between_python
How to Extract String Between Two Characters or Strings in Python - stataiml
May 3, 2024 - You can extract a string between two characters or strings in Python using various functions such as search() (from re package) and split() functions.
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.
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. You have to import the re module for this example. Apply re.search(pattern, string) with the pattern set to “x(.*?)y” to match substrings that begin with “x” and end with “y” and use Match.group() to get the desired substring.
Top answer 1 of 4
30
Tweeky way!
>>> char1 = '('
>>> char2 = ')'
>>> mystr = "mystring(123234sample)"
>>> print mystr[mystr.find(char1)+1 : mystr.find(char2)]
123234sample
2 of 4
10
$ is a special character in regex (it denotes the end of the string). You need to escape it:
>>> re.findall(r'\
', '
is an function of x')
['sin (x)']
YouTube
youtube.com › watch
Find text between two characters in Python - YouTube
In this simple tutorial I will show you how we can extract a text in a string that exists between two specific characters.
Published: August 28, 2017
GameDev.net
gamedev.net › forums › topic › 681023-python-get-string-between-two-characters
Python-Get String Between Two Characters - For Beginners - GameDev.net
August 12, 2016 - You could replace these with an empty string. Then use re.split with either the '^' or '>' characters. You have to escape '^' because it has special meaning to a regular expression. Using the pipe character creates an or condition in a regular expression. Then that would give me results but they would have a lot of whitespace, so I would use a list comprehension to get rid of the extra whitespace and to omit any blank entries from the list. ... #!/usr/bin/env python import re def main(): target = ' ~~~~ ABC ^ DEF ^ HGK > LMN ^ ' target = target.replace('~', '') target_list = re.split('\^|>', target) target_list = [entry.strip() for entry in target_list if len(entry.strip()) > 0] print(target_list) if __name__ == '__main__': main()
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.
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 the regex pattern to match content between the delimiters pattern = r"\[(.*?)\]" # Search for the pattern in the input string match = re.search(pattern, s) # Check if a match is found and extract the substring if match: result = match.group(1) print(result) # Output: world else: print("Delimiters not found")
Python Guides
pythonguides.com › extract-a-substring-between-two-characters-in-python
How To Extract A Substring Between Two Characters In Python?
March 19, 2025 - We first find the index of the starting character index() and add its length to get the starting index of the substring. Then, we find the index of the ending character, starting from the previously found index. Finally, we use slice notation to extract the substring between these two indices. Read How to Fix Unterminated String Literals in Python?
Top answer 1 of 3
15
Regular expressions
import re
matches = re.findall(r'<p>.+?</p>',string)
The following is your text run in console.
>>>import re
>>>string = """<p>I'd like to find the string between the two paragraph tags.</p><br><p>And also this string</p>"""
>>>re.findall('<p>.+?</p>',string)
["<p>I'd like to find the string between the two paragraph tags.</p>", '<p>And also this string</p>']
2 of 3
13
If you want the string between the p tags (excluding the p tags) then add parenthesis to .+? in the findall method
import re
string = """<p>I'd like to find the string between the two paragraph tags.</p><br><p>And also this string</p>"""
subStr = re.findall(r'<p>(.+?)</p>',string)
print subStr
Result
["I'd like to find the string between the two paragraph tags.", 'And also this string']
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.
Finxter
blog.finxter.com › home › learn python blog › python | split string between characters
Python | Split String Between Characters - Be on the Right Side of Change
November 30, 2022 - It will return a tuple that consists of two items. The first item will be the entire given string and the second item will have the required substring. Hence, we will extract the second item from the tuple using its index to get the final string between the characters. ... import re # Given text = "Learn Python 3.9 from scratch" left = "Learn" right = "from scratch" result = re.search('%s(.*)%s' % (left, right), text).group(1) print(result) # Python 3.9