Regex To Match Spaces And Empty Lines That Aren’t In Quotes

Want to match a pattern of spaces and empty lines, but want it isolated from quotes? I often want to find all spaces and empty lines in a string (that are not enclosed in quotes), whether they are inside or outside of a string. However, I’ve found it exceedingly difficult to find good regex examples for this problem. So I’ve found one.

You can use this regex to replace all spaces and empty lines that reside outside of a quote, with nothing. What that means is that all spaces and empty lines outside of a quote will be removed from the string, or match.

/\s+(?=([^"]*"[^"]*")*[^"]*$)/g

Matches:

  • Any spaces but Aren’t In Quotes
  • Any empty lines

Non-matches:

  • ” “

See Also:

Regex Is Copied!