[Tutor] changing string in place

Paul McGuire ptmcg at austin.rr.com
Sat Jan 10 16:32:19 CET 2009


Sometimes pyparsing is less stressful than struggling with RE's
typoglyphics, especially for a one-off conversion (also note handling of
quoted strings - if a 'new Date(y,m,d)' occurs inside a quoted string, this
script *won't* convert it):

from pyparsing import nums,Word,Literal,quotedString

# parse a number, return it as an int
num = Word(nums).setParseAction(lambda t:int(t[0]))

# format of a json 'new Date' - assign names to date fields
newdate = ( Literal("new") + "Date" + '(' + 
    num("year") + ',' + num("month") + ',' + num("day") + 
    ')' )

# parse action to convert dates
def reformatDate(t):
    t["month"] += 1
    return '"%(year)04d-%(month)02d-%(day)02d"' % t
newdate.setParseAction( reformatDate )

# do conversions - explicit parsing of quoted strings 
# will skip over "new Date" strings if there are any 
# enclosed in quotes
print (quotedString | newdate).transformString(s)


-- Paul



More information about the Tutor mailing list