Problem with regular expression

Paul McGuire ptmcg at
Sun Mar 7 15:10:55 CET 2010

On Mar 7, 4:32 am, Joan Miller <pelok... at> wrote:
> I would to convert the first string to upper case. But this regular
> expression is not matching the first string between quotes.
Is using pyparsing overkill?  Probably.  But your time is valuable,
and pyparsing let's you knock this out in less time than it probably
took to write your original post.

Use pyparsing's pre-defined expression sglQuotedString to match your
entry key in quotes:

    key = sglQuotedString

Add a parse action to convert to uppercase:

    key.setParseAction(lambda tokens:tokens[0].upper())

Now define the rest of your entry value (be sure to add the negative
lookahead so we *don't* match your foo entry):

    entry = key + ":" + ~Literal("{")

If I put your original test cases into a single string named 'data', I
can now use transformString to convert all of your keys that don't
point to '{'ed values:

    print entry.transformString(data)

Giving me:

    # string to non-matching
    'foo': {

    # strings to matching
    'BAR': 'bar2'
    'BAR': None
    'BAR': 0
    'BAR': True

Here's the whole script:

    from pyparsing import sglQuotedString, Literal

    key = sglQuotedString
    key.setParseAction(lambda tokens:tokens[0].upper())
    entry = key + ":" + ~Literal("{")

    print entry.transformString(data)

And I'll bet that if you come back to this code in 3 months, you'll
still be able to figure out what it does!

-- Paul

More information about the Python-list mailing list