How to break into spaces not between quotes?

I am trying to split the line only into white spaces ( \s ), but this is not between the "quoted" section.

I map the entire text between these cited sections as follows:

 (['"`]).*?\1 

Regex101

However, when I try to add this as a negative look, to separate only the white spaces outside these quotes, I cannot get it to work:

 \s(?!(['"`]).*?\1) 

Regex101

How can I separate only spaces that are not in quotation marks?

+7
javascript split regex
source share
3 answers
 \s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$) 

You can use this regex with lookahead to separate. See the demo.

https://regex101.com/r/5I209k/4

or mixed tics.

https://regex101.com/r/5I209k/7

+7
source share

The problem is that you need to exclude entries within the group. Instead of using a negative look, you can do it like this:

 (\S*(?:(['"`]).*?\2)\S*)\s?|\s 

Basically, he does this:

  • captures any characters without spaces
    • which may contain a quoted string
    • and optionally any non-spaces immediately follow (for example, a comma after the quote).
  • then matches optional trailing spaces

OR

  • matches one space

Then capture group 1 will contain as long as possible sequences of all characters without spaces (if they are not indicated in quotation marks). Thus, this can be used with the replacement group \1\n to replace your desired spaces with a new line.

Regex101: https://regex101.com/r/A4HswJ/1

JSFiddle: http://jsfiddle.net/u1kjudmg/1/

+2
source share

I would use a simpler approach without the need for additional features:

 '[^']*'|"[^"]*"|`[^`]*`|\S* 

value:

  • one-step section '[^']*'
  • or | section with two quotation marks "[^"]*"
  • or | section with a back link (cannot put it in the string designation SO)
  • or | unquoted section \S+

This will also separate the parts quoted. If this is not necessary, you can use

 ("[^"]*"|'[^']*'|`[^`]*`|\S)+ 

i.e. find sequences of tokens where each token is either a non-decomposition or a quotation mark.

+1
source share

All Articles