Python Forum
string between two strings - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: string between two strings (/thread-1225.html)



string between two strings - Skaperen - Dec-15-2016

i want to get the string that is between (the first instances of) two strings, a and b (in that order).  i can do it like:

what_was_between = original_string.split(a)[1].split(b)[0]
is there a shorter, sweeter, and/or more elegant way?  i am dreaming of:

def between(s,a,b):
    return s.split(a)[1].split(b)[0]
should i go with that?


RE: string between two strings - micseydel - Dec-15-2016

I think a regular expression is the way to go, if you're looking for simplicity. A regex will also have the advantage of performance, having been optimized in C, and efficiency, doing the minimum string traversal and not needing to create intermediate strings.


RE: string between two strings - Skaperen - Dec-15-2016

(Dec-15-2016, 05:10 AM)micseydel Wrote: I think a regular expression is the way to go, if you're looking for simplicity. A regex will also have the advantage of performance, having been optimized in C, and efficiency, doing the minimum string traversal and not needing to create intermediate strings.

can that be done in cases where the bounding strings or the string to extract are regular expressions, or subsets or supersets of them?

edit1:

the first (but not the only) project using this will be extracting from between constants '<' and '>'.


RE: string between two strings - Ofnuts - Dec-15-2016

(Dec-15-2016, 08:39 AM)Skaperen Wrote: the first (ut not the only) project using this will be extracting from between constants '<' and '>'.


http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#1732454