regex 正则表达式将命令行拆分为参数,同时保留破折号?

0md85ypi  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(66)

给定一个命令行,如:

some\path to\an\executable.exe -foo --bar-baz abc\d e --qux -tux 123 --vux 456 --

我想得到一个看起来像这样的数组:

some\path to\an\executable.exe
-foo
--bar-baz abc\d e
--qux
-tux 123
--vux 456
--

我试过使用像(?=-)这样的正则表达式,但是它在--的args和中间有-的args上失败了,比如--foo-bar。我不能在空格上拆分,因为args可能是包含空格的路径。

ttvkxqim

ttvkxqim1#

你的正则表达式(?=-)应该可以工作,它只需要在lookahead之前使用\s

$theExample = 'some\path to\an\executable.exe -foo --bar-baz abc\d e --qux -tux 123 --vux 456 --'
$theExample -split '\s(?=-)'

这将输出你想要的东西。请参见https://regex101.com/r/YOeQE3/1
我相信linked answer provided in comments为这个问题提供了一个更健壮的解决方案,但是正如你所说的,路径没有引号,可能有空格,在这种情况下,你需要在使用它之前自己引用它们。
在这种情况下,这可能会有所帮助:

$theExample = 'some\path to\an\executable.exe -foo --bar-baz abc\d e --qux -tux 123 --vux 456 --'
$theExample -replace '^(?!["''])[a-z \\.:]+(?=\s-)', '''$0'''

请参见https://regex101.com/r/Y5l5KU/2

相关问题