You could try the below positive lookahead based regex.
\s(?=(?:"[^"]*"|[^"])*$)
or
(?=(?:"[^"]*"|[^"])*$)
DEMO
Explanation:
Take foo "foo bar" buz
as an example string.
foo "foo bar" buz
\s
at first matches all the spaces. Then it checks the condition that the matched spaces must be followed by double quoted string or [^"]
zero or more times. So it checks that the first space if followed by a double quoted string or not. Yes, the first space if followed by a double quoted string "foo bar"
, then the character following the double quoted string is a space. Now the regex "[^"]*"
got failed and the control switches to the next part ie,
[^"]
. This pattern matches the following space. Because *
applies to that pattern [^"]*
matches all the following characters. Finally the condition is satisfied for the first space, so it got matched.