Problem with regular expression
Steve Holden
steve at holdenweb.com
Sun Mar 7 08:03:08 EST 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)
>
> # 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'
>
>
> Any help? please
> Thanks in advance
Well your pattern is identifying the right bits, but re.sub() replaces
everything it matches:
>>> import re
>>> strings = """\
... 'bar': 'bar2'
... 'bar': None
... 'bar': 0
... 'bar': True""".split("\n")
>>> for s in strings:
... print re.sub("'(?P<id>\w+)': [^{]", "\g<id>FOO", s)
...
barFOObar2'
barFOOone
barFOO
barFOOrue
>>>
What you need to fix is the replacement. Take a look at the
documentation for re.sub: you will need to provide a function to apply
the upper-case transformation, and the example there should show you how.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list