Regex substitution trouble

Chris Angelico rosuav at gmail.com
Tue Oct 28 07:24:42 EDT 2014


On Tue, Oct 28, 2014 at 10:02 PM,  <massi_srb at msn.com> wrote:
> I'm not really sure if this is the right place to ask about regular expressions, but since I'm usin python I thought I could give a try :-)

Yeah, that sort of thing is perfectly welcome here. Same with
questions about networking in Python, or file I/O in Python, or
anything like that. Not a problem!

> Here is the problem, I'm trying to write a regex in order to substitute all the occurences in the form $"somechars" with another string. This is what I wrote:
>
> newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring)
>
> This works pretty well, but it has a problem, I would need it also to handle the case in which the internal string contains the double quotes, but only if preceeded by a backslash, that is something like $"somechars_with\\"doublequotes".
> Can anyone help me to correct it?

But this is a problem. You can use look-ahead assertions and such to
allow the string \" inside your search string, but presumably the
backslash ought itself to be escapable, in order to make it possible
to have a loose backslash legal at the end of the string. I suggest
that, instead of a regex, you look for a different way of parsing.
What's the surrounding text like?

ChrisA



More information about the Python-list mailing list