I’m trying to select the spaces at the beginning and end of a quote that’s a part of a larger string. Once selected, I will remove these leading/trailing whitespaces. I need to do this without using trim().
Here are a bunch of strings with ideal solutions to better illustrate my point:
red " blue " green!
=>red "blue" green!
" red blue green "
=>"red blue green"
" red " " blue " " green "
=>"red" "blue" "green"
This is the closest I’ve gotten to solving this problem:
s+(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)
The Regex correctly locates the leading and ending whitespaces in the examples above, but it fails when multiple words are within the quotes. It only works when 1 word is within the quotes.
2
Answers
If you want to remove these spaces, you can use
See this demo at regex101 or a JS demo at tio.run
The pattern is simple, it captures lazily any amount of non-quotes surrounded by optional space within quotes. It would do some superfluous replacements as well but won’t lose balance.
If you need to support escaped quotes inside the string you can modify the @bobble bubble regex like this:
Here’s a preview on regex101.