re sub help

Mike Meyer mwm at mired.org
Sat Nov 5 02:22:59 EST 2005


s99999999s2003 at yahoo.com writes:

> hi
>
> i have a string :
> a =
> "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n"
>
> inside the string, there are "\n". I don't want to substitute the '\n'
> in between
> the [startdelim] and [enddelim] to ''. I only want to get rid of the
> '\n' everywhere else.

Well, I'm not an expert on re's - I've only been using them for three
decades - but I'm not sure this can be done with a single re, as the
pattern you're interested in depends on context, and re's don't handle
that well.

On the other hand, this is fairly straightforward with simple string
operations:

>>> a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n"
>>> sd = '[startdelim]'
>>> ed = '[enddelim]'
>>> s, r = a.split(sd, 1)
>>> m, e = r.split(ed, 1)
>>> a = s + sd + m.replace('\n', '') + ed + e
>>> a
'this\nis\na\nsentence[startdelim]thisisanother[enddelim]this\nis\n'
>>> 

    <mike

-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list