Capture text from colon back to comma or start of line

I need to create a javascript regex that will grab the css selector.

Here are some examples:

*, ::before, ::after // do not capture anything
::before // do not capture anything
.class1, .class2:before,.class3::after // capture .class2 and .class3
.class4::before // capture .class4
.class-5::before // capture .class-5
.class__6::after // capture .class__6
.class--7 > .child::after // capture .class--7 > .child
#id1 + .something:after // capture #id1 + .something
#id2[attribute-one="1"] + .class8:before // capture #id2[attribute-one="1"] + .class8


Here's what I have : /([.#\-+~>\[\]\"\'=\w ]+)(?=:?:)/g

. This is not ideal because I essentially need to whitelist special characters.

Instead, I would rather do something like:

  • Find the colon
  • Go back until I close the comma or the beginning of the line.

Bonus points for ignoring single spaces, so

*, ::before


will not write a space after the comma.

Note. This is essentially a more complex version of this question


source to share

2 answers

You can use this regex:



And capture captured group # 1 for your matches.

Demo version of RegEx





Try this.It gives all the match.See demo.



All Articles