I need to split an input string at contiguous spaces into a list of strings. The input may include single or double quoted strings, which must be ignored.
How can I split a string at the spaces, but ignore quoted strings, so the result of splitting this
me you "us and them" 'everyone else' them'
returns this?
me
you
us and them
everyone else
them
Duplicate of this question but for needing to ignore single-quoted strings, as well.
This excellent solution has been modified to ignore single-quoted strings, as well, and remove all leading and trailing quotes from each argument.
$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 '^["'']|["'']$', ''
Results in:
me
you
us and them
everyone else
them
In short, this regex matches a string of blanks so long as everything that follows is a non-quote or a quoted string–effectively treating quoted strings as single characters.