Parsing a search string

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Fri Dec 31 10:06:24 EST 2004


Freddie wrote:
> Happy new year! Since I have run out of alcohol, I'll ask a question that I 
> haven't really worked out an answer for yet. Is there an elegant way to turn 
> something like:
> 
>  > moo cow "farmer john" -zug
> 
> into:
> 
> ['moo', 'cow', 'farmer john'], ['zug']
> 
> I'm trying to parse a search string so I can use it for SQL WHERE constraints, 
> preferably without horrifying regular expressions. Uhh yeah.

The shlex approach, finished:

searchstring = 'moo cow "farmer john" -zug'
lexer = shlex.shlex(searchstring)
lexer.wordchars += '-'
poslist, neglist = [], []
while 1:
    token = lexer.get_token()
    # token is '' on eof
    if not token: break
    # remove quotes
    if token[0] in '"\'':
        token = token[1:-1]
    # select in which list to put it
    if token[0] == '-':
        neglist.append(token[1:])
    else:
        poslist.append(token)

regards,
Reinhold



More information about the Python-list mailing list