Robins Gupta
Robins Gupta

Reputation: 3153

REGEX: Finding the correct occurrence order of some given special characters in a string

I want a regular expression that would be able to find the correct occurrence order of

* | . | # | 'any HTML element type' like '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 am trying my luck with regex = /^\*?[a-zA-Z]*|\#|\./g but it doesn't work

Upvotes: 0

Views: 360

Answers (2)

Jake Aitchison
Jake Aitchison

Reputation: 1099

ok I have:

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

the problem with this is that unless you specify all the possible html elements that you can capture like div, span etc then it will match all strings including class and id names.

Hope this helps anyway.

Regular expression visualization

Edit live on Debuggex

Upvotes: 0

georg
georg

Reputation: 214969

You might be better off matching # and . along with their respective values and filtering the results afterwards:

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

or remove the id/class names first, and then match:

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

Upvotes: 2

Related Questions