提问人:i_am_jorf 提问时间:9/27/2023 更新时间:9/27/2023 访问量:53
正则表达式将命令行拆分为参数,同时保留破折号?
Regex to split a command line into args, while preserving dashes?
问:
给定一个命令行,如下所示:
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
答:
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'''
评论