best way to parse a function-call-like string?

Paul McGuire ptmcg at austin.rr.com
Thu Feb 26 17:56:17 EST 2009


On Feb 26, 3:29 pm, m... at pixar.com wrote:
> I have some strings that look like function calls, e.g.
>
>         "junkpkg.f1"
>         "junkpkg.f1()"
>         "junkpkg.f1('aaa')"
>         "junkpkg.f1('aaa','bbb')"
>         "junkpkg.f1('aaa','bbb','ccc')"
>         "junkpkg.f1('aaa','with,comma')"
>
> and I need to split them into the function name and list of parms, e.g.
>

Pyparsing will easily carve up these function declarations, and will
give you some room for easy extension once your parsing job starts to
grow to include other variants (like arguments other than quoted
strings, for instance).  Using the results names ("name" and "args"),
then parsed fields are easy to get at after the parsing is done.

-- Paul

from pyparsing import Word, alphas, alphanums, delimitedList, \
    Optional, Literal, Suppress, quotedString

LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas+"_", alphanums+"_")
fnName = delimitedList(ident,".",combine=True)
arg = quotedString
fnCall = fnName("name") + Optional(LPAR +
        Optional(delimitedList(arg)) + RPAR, default=[])("args")

tests = """junkpkg.f1
        junkpkg.f1()
        junkpkg.f1('aaa')
        junkpkg.f1('aaa','bbb')
        junkpkg.f1('aaa','bbb','ccc')
        junkpkg.f1('aaa','with,comma')""".splitlines()

for t in tests:
    fn = fnCall.parseString(t)
    print fn.name
    for a in fn.args:
        print "-",a
    print

Prints:

junkpkg.f1

junkpkg.f1

junkpkg.f1
- 'aaa'

junkpkg.f1
- 'aaa'
- 'bbb'

junkpkg.f1
- 'aaa'
- 'bbb'
- 'ccc'

junkpkg.f1
- 'aaa'
- 'with,comma'



More information about the Python-list mailing list