标记命令字符串

时间:2010-04-27 16:31:23

标签: python regex

我有这样的字符串:

command ". / * or any other char like this" some_param="string param" some_param2=50

我想将此字符串标记为:

command
". / * or any other char like this"
some_param="string param"
some_param2=50

我知道可以用空格分割,但这些参数也可以用逗号分隔,例如:

command ". / * or any other char like this", some_param="string param", some_param2=50

我试着这样做:

\w+\=?\"?.+\"?

但它不起作用。

2 个答案:

答案 0 :(得分:3)

stdlib模块shlex用于解析类似shell的命令语法:

>>> import shlex
>>> s = 'command ". / * or any other char like this" some_param="string param" some_param2=50'
>>> shlex.split(s)
['command', '. / * or any other char like this', 'some_param=string param', 'some_param2=50']

与您期望的结果的唯一区别在于引用的字符串作为字符串值返回,而不是作为引用的字符串文字返回。

答案 1 :(得分:2)

这样的东西?

>>> x='command ". / * or any other char like this" some_param="string param" some_param2=50'
>>>
>>> re.findall('\w+\=\d+|\w+\="[^"]+"|"[^"]+"|\w+',x)
['command', '". / * or any other char like this"', 'some_param="string param"', 'some_param2=50']
>>>