Regex substitution trouble

Tim jtim.arnold at gmail.com
Tue Oct 28 17:38:00 CET 2014


On Tuesday, October 28, 2014 7:03:00 AM UTC-4, mass... at msn.com wrote:
> Hi everyone,
> 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 :-)
> 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?
> Thanks in advance!

You have some good answers already, but I wanted to let you know about a tool you may already have which is useful for experimenting with regexps. On windows, the file `redemo.py` is in the Tools/Scripts folder. 

If you're on a Mac, see http://stackoverflow.com/questions/1811236/how-can-i-run-redemo-py-or-equivalent-on-a-mac

It has really helped me work on some tough regexps.
good luck,
--Tim



More information about the Python-list mailing list