用于解析函数命令行参数的正则表达式

时间:2015-03-22 12:47:53

标签: c regex

我如何解析以下函数命令行: separtor是(\ s- \ w \ s),如-c或-d或-n

C:/my app/bin/Reader.dll -n Proc_20ms -c C:/Users/Braun/Desktop/test.csv -t Continue the simulation from the first line of the csv-file -j none -V errors and warnings (default) -d ,

为:

Match1:  C:/my app/bin/Reader.dll
Match2: -n
Match3: Proc_20ms
Match4: -c
Match5: C:/Users/Braun/Desktop/test.csv
Match6: -t
Match7: Continue the simulation from the first line of the csv-file 
Match8: -j
Match9: none
Match10: -V
Match11: errors and warnings (default)
Match12: -d
Match13: ,

感谢。

1 个答案:

答案 0 :(得分:1)

只需将-\w放入捕获组,然后在re.split函数中使用此正则表达式。捕获组是必要的,因此它将保留分隔符(即,只有捕获组内存在的字符)。

>>> s = 'C:/my app/bin/Reader.dll -n Proc_20ms -c C:/Users/Braun/Desktop/test.csv -t Continue the simulation from the first line of the csv-file -j none -V errors and warnings (default) -d ,'
>>> for i in re.split(r'\s(-\w)\s', s):
        print(i)


C:/my app/bin/Reader.dll
-n
Proc_20ms
-c
C:/Users/Braun/Desktop/test.csv
-t
Continue the simulation from the first line of the csv-file
-j
none
-V
errors and warnings (default)
-d
,