Regex splits string into specific characters outside quotes

How can I split this string while saving quoted strings

>div#a.more.style.ui[url="in.tray"]{value}

where are the characters to break

> # . [ {

To obtain:

>div
#a
.more
.style
.ui
[url="in.tray"]
{value}

Current effort:

\>|\[|\{|#|\.?(?:(["'])(?:\\?.)*?\1)*

with section "in.tray".

Update 1:

The solution should be regular, because the template is assembled from the keys of the JS object in the existing code, which:

JSObject
    '>': function ...
    '^': function ...
    '[': function ...
     ...

with functions used as callbacks to handle regexp output.

The target line represents a macro Emmet and simple symbols may comprise for starting and possible recurrence of at least ^, $for processing as separate elements, for example:

p>div>div>span^h2^^h1>div#a.li^mo+re.st*yle.ui[url="in.tray"]{value}$$$

Current efforts based on @ tim-pietzcker , using .match(), but with a blank last filtered response:

[a-z$^+*>#.[{]{0,1}(?:"[^"]*"|[^"$^+*>#.[{]){0,}

+4
3

split(), :

result = subject.match(/[>#.[{](?:"[^"]*"|[^">#.[{])+/g);

regex101.com.

:

[>#.[{]     # Match a "splitting" character
(?:         # Start of group to match either...
 "[^"]*"    # a quoted string
|           # or
 [^">#.[{]  # any character except quotes and "splitting" characters
)+          # Repeat at least once.
+4

, .

:

var i=0, s= '>div#a.more.style.ui[url="in.tray"]{value}';
var tokens = s.replace(/("[^"]+"|[^"\s]+)/g, function(v){
     return (i++)%2 ? v : v.replace(/([.>#\[{])/g, '@@@$1')}
).split('@@@').filter(Boolean);

( @@@ , , .

  • ( , - ) ( , )
  • , @@@
  • split on @@@
  • () filter
+1

, Regex - . , regex, , :

var string = '>div#a.more.style.ui[url="in.tray"]{value}'
var delims = [ '>', '#', '.', '[', '{' ];
var inQuotes = false;
var parts = [];
var part = string[0]; // Start with first character

for(i = 1; i < string.length; i++) {
  var character = string[i];

  if(character == '"') inQuotes = !inQuotes;

  if(!inQuotes && delims.indexOf(character) > -1) {
    parts.push(part);
    part = character;
  } else part += character;

  if(i == string.length-1) parts.push(part);
}

console.log(parts);

:

[ '>div',
  '#a',
  '.more',
  '.style',
  '.ui',
  '[url="in.tray"]',
  '{value}' ]

inQuotes , .. "He said, \"hi there!\"", , , . , , , "\" , isQuotes true, , , , .

, , Regex.

-1

Source: https://habr.com/ru/post/1532455/


All Articles