re.sub and named groups

Yapo Sébastien sebastien.yapo at free.fr
Wed Feb 4 12:36:56 EST 2009


> Hi everybody,
>
> I'm having a ball with the power of regular expression but I stumbled
> on something I don't quite understand:
>
> theOriginalString = "spam:(?P<first>.*) ham:(?P<second>.*)"
> aReplacementPattern = "\(\?P<first>.*\)"
> aReplacementString= "foo"
> re.sub(aReplacementPattern , aReplacementString, theOriginalString)
>
> results in :
>
> "spam:foo"
>
> instead, I was expecting:
>
> "spam:foo ham:"
>
> Why is that?
>
> Thanks for your help!
>
> Manu
>
>   
I think that .* in your replacement pattern matches ".*)
ham:(?P<second>.*" in your original string which seems correct for a regexp.
Perhaps you should try aReplacementPattern = "\(\?P<first>\.\*\)" or use
replace() since your replacement pattern is not a regexp anymore.

Sebastien



More information about the Python-list mailing list