REGEX: search for the correct order of occurrence of some given characters in a string

I want a regular expression that can find the correct order of occurrence

* |, | # | "any type of HTML element", such as "p" or "div"

LIKE

var regex = //Some regular expression; var pattern_1 = "*p.class1#id1.class2"; pattern_1.match(regex); // Should print ['*','p','.','#','.'] var pattern_2 = "p.class1#id1.class2"; pattern_2.match(regex); //Should print ['p','.','#','.'] var pattern_3 = "p#id1.class1.class2"; pattern_3.match(regex); //Should print ['p','#','.','.'] var pattern_4 = "#id.class1.class2"; pattern_4.match(regex); //should print ['#id','.','.'] var pattern_5 = "*#id.class1.class2"; pattern_5.match(regex); //should print ['*','#','.','.'] 

I'm trying good luck with regex = /^\*?[a-zA-Z]*|\#|\./g , but it does not work

0
source share
2 answers

You might be better off matching # and . along with their respective values ​​and then filter the results:

  var regex = /\*|([#.]\w+)|(\w+)/g matches = pattern_1.match(regex).map(function(x) { return x.match(/^[#.]/) ? x.charAt(0) : x }) 

or first remove the id / class names and then follow these steps:

  matches = pattern_1.replace(/([#.])\w+/g, "$1").match(/[.#*]|\w+/g) 
+2
source

ok I have:

 /(\*)|(\.)|([a-zA-Z]+)|(#)/g 

the problem is that if you do not specify all the possible html elements that you can write as div , span , etc., then it will correspond to all lines, including class names and identifiers.

Hope this helps anyway.

Regular expression visualization

Change live in Debuggex

0
source

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


All Articles