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

问题描述 投票:0回答:1

给出如下命令行:

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
--

我尝试使用像

(?=-)
这样的正则表达式,但是在
--
'd 参数和中间带有
-
的参数(如
--foo-bar
)上会崩溃。我无法按空格分割,因为 args 可能是其中包含空格的路径。

regex powershell split
1个回答
0
投票

你的正则表达式

(?=-)
应该可以工作,它只需要在前瞻之前
\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

我相信评论中提供的链接答案为问题提供了更强大的解决方案,但正如您所说,路径没有被引用,并且可能有空格,在这种情况下,您需要在使用该解决方案之前自己引用它们。在这种情况下这可能会有所帮助:

$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/1

© www.soinside.com 2019 - 2024. All rights reserved.