Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find string between two substrings [duplicate]

How do I find a string between two substrings ('123STRINGabc' -> 'STRING')?

My current method is like this:

>>> start = 'asdf=5;' >>> end = '123jasd' >>> s = 'asdf=5;iwantthis123jasd' >>> print((s.split(start))[1].split(end)[0]) iwantthis 

However, this seems very inefficient and un-pythonic. What is a better way to do something like this?

Forgot to mention: The string might not start and end with start and end. They may have more characters before and after.

like image 466
John Howard Avatar asked Jul 30 '10 05:07

John Howard


People also ask

How do you get a string between two substrings in Python?

To find a string between two strings in Python, use the re.search() method. The re.search() is a built-in Python method that searches a string for a match and returns the Match object if it finds a match. If it finds more than one match, it only returns the first occurrence of the match.

How do you search for two strings in Python?

You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any .


1 Answers

import re  s = 'asdf=5;iwantthis123jasd' result = re.search('asdf=5;(.*)123jasd', s) print(result.group(1)) 
like image 54
Nikolaus Gradwohl Avatar answered Sep 20 '22 19:09

Nikolaus Gradwohl