Problem with regular expression

Tim Chase python.list at
Sun Mar 7 14:35:31 CET 2010

Joan Miller wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
>   re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", str)

Well, my first thought is that you're not using raw strings, so 
you're not using the regexps and replacements you think you are.

   r"'(?P<id>\w+)': [^{]"

will match the lines of interest.  The replacement will eat the 
opening & closing single-quote, colon, and first character.

> # string to non-matching
> 'foo': {
> # strings to matching
> 'bar': 'bar2'
> 'bar': None
> 'bar': 0
> 'bar': True
> So, i.e., from the first string I would to get:
>   'BAR': 'bar2'

I think you'd have to use a function/lambda to do the 

     r"'(?P<id>\w+)(?=': [^{])",
     lambda m: "'" +'id').upper(),

Or you could just forgo regexps and use regular string functions 
like split(), startswith(), and upper()


More information about the Python-list mailing list