Splitting on a regex w/o consuming delimiter

Lemniscate d_blade8 at hotmail.com
Mon Nov 12 00:39:59 EST 2001


Nadav Horesh <Nadavh at envision.co.il> wrote in message news:<mailman.1005469891.21795.python-list at python.org>...
> Whats about:
>  >>> st = 'This @is a @modul@ ar trr'
>  >>> re.split(".(?=@)", st)
> 
> ['This', '@is a', '@modu', '@ ar trr']
> 
> Nadav.

Actually, I like this one, and you can do it an infinite number of
ways (take a look at <i> Mastering Regular Expressions </i> by
O'Reilly for a better idea of why using regular expressions can be
tricky (like trying to split something and losing what you split). 
Personally, I would go like the above, but let's try something else,
like maybe (and you can hide this in a function, I just do it here
interactively):

st = 'This @is a @modul@ ar trr'
xl = []
while st.find('@') != -1:
     xl.append(st[st.rfind('@'):])
     st = st[:st.rfind('@')]
 
xl.append(st)
xl.reverse()
print xl
    gives
['This ', '@is a ', '@modul', '@ ar trr']



Put something like it into a function/class (depending on what you
need to do with the results, I guess).  Maybe pass in two parameters,
a string and a seperator.  Then you just call the fucntion to get your
result. Maybe something like:

def StringSep(YourString, sep):
     newlist = []
     while YourString.find(sep) != -1:
          newlist.append(YourString[YourString.rfind(sep):])
          YourString = YourString[:YourString.rfind(sep)]
     xl.append(YourString)
     xl.reverse()
     return xl


Keep in mind, I've kept it simple but you can feed in seps that are
bigger than one digit, you would just have to do some initial coding,
then you would be home free.

Later



More information about the Python-list mailing list