全部,我试图解析用户的指令(存储为单行字符串),具有以下特征:
输入和所需解析的示例(显示为字典);单引号开始和结束示例,并且不是要解析的字符串的一部分..:
'start'
{'cmd':'start'}
' stop '
{'cmd':'stop'}
'start now'
{'cmd':'start','arg1':'now'}
' start later forward , back '
{'cmd':'start','arg1':'later','arg2':'forward','arg3':'back}
'start tomorrow ,back, "Lucile, Michael " Oscar'
{'cmd':'start','arg1':tomorrow','arg2':'back','arg3':'Lucile, Michael','arg4':'Oscar'}
我参与PY3.4,但关键问题是RegEx,不需要特定于python的实现。
答案 0 :(得分:1)
单个正则表达式可能更难,因为看起来您可能想要处理任意数量的参数。您可以使用此函数以上面给出的格式提取命令和参数:
import re
def parse(s):
args = {}
n = 1
# recognizes a double-quoted argument
q_arg_re = "^\s*,?\s*\"(.*?)\""
# recognizes a single-word argument
arg_re = "^\s*,?\s*(\w+)"
arg = False
while True:
m = re.search(arg_re, s)
if m:
arg = m.groups()[0]
else:
m = re.search(q_arg_re, s)
if m:
arg = m.groups()[0]
if arg:
if 'cmd' in args:
args['arg{}'.format(n)] = arg
n += 1
else:
args['cmd'] = arg
s = s[m.end(0):]
arg = False
else:
break
return args
答案 1 :(得分:0)