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

Regex to split a command line into args, while preserving dashes?

提问人:i_am_jorf 提问时间:9/27/2023 更新时间:9/27/2023 访问量:53

问:

给定一个命令行,如下所示:

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 args 和中间带有 a 的 args,例如 .我不能在空格上拆分,因为 args 可能是包含空格的路径。(?=-)-----foo-bar

正则表达式 PowerShell 拆分

评论

3赞 Wiktor Stribiżew 9/27/2023
你在解析命令行吗?查看 stackoverflow.com/questions/67536569/...
0赞 i_am_jorf 9/27/2023
这会正确解析带空格的非带引号的路径吗?我在这里的目标是采用我无法控制的进程输出的命令行并修复不带引号的路径。
1赞 Santiago Squarzon 9/27/2023
什么决定了带空格的不带引号的路径的结尾?它总是有扩展吗?如果是这样,您可以使用正则表达式引用它,然后使用带有 AST 的链接答案中显示的方法

答:

1赞 Santiago Squarzon 9/27/2023 #1

你的正则表达式应该可以工作,它只需要在前瞻之前:(?=-)\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/2