我需要将连续空格处的输入字符串拆分为字符串列表。输入可能包含单引号或双引号字符串,必须忽略它们。
如何在空格处分割字符串,但忽略带引号的字符串,所以分割的结果
me you "us and them" 'everyone else' them'
返回这个?
me
you
us and them
everyone else
them
这个问题的重复,但也需要忽略单引号字符串。
这个优秀的解决方案已被修改为忽略单引号字符串,并删除每个参数中的所有前导和尾随引号。
$people = 'me you "us and them" ''everyone else'' them'
$pattern = '(?x)
[ ]+ # Split on one or more spaces (greedy)
(?= # if followed by one of the following:
(?:[^"'']| # any character other a double or single quote, or
(?:"[^"]*")| # a double-quoted string, or
(?:''[^'']*'')) # a single-quoted string.
*$) # zero or more times to the end of the line.
'
[regex]::Split($people, $pattern) -replace '^["'']|["'']$', ''
结果:
me
you
us and them
everyone else
them
简而言之,只要后面的所有内容都是非引号或带引号的字符串,此正则表达式就会匹配空格字符串 - 有效地将带引号的字符串视为单个字符。