This question already has an answer here:
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.
You can simply use this code or copy the function below. All neatly in one line.
If you run the function as follows.
You will pobably be left with the output:
rather than
If you want to have the sub-strings on the end of the output the code must look like below.
But if you don't want the substrings on the end the +1 must be on the first value.
Parsing text with delimiters from different email platforms posed a larger-sized version of this problem. They generally have a START and a STOP. Delimiter characters for wildcards kept choking regex. The problem with split is mentioned here & elsewhere - oops, delimiter character gone. It occurred to me to use replace() to give split() something else to consume. Chunk of code:
Just converting the OP's own solution into an answer:
Further from Nikolaus Gradwohl answer, I needed to get version number (i.e., 0.0.2) between('ui:' and '-') from below file content (filename: docker-compose.yml):
and this is how it worked for me (python script):
Here is a function I did to return a list with a string(s) inbetween string1 and string2 searched.
Result:
re_find
was almost 20 times slower thanindex_find
in this example.