Regex to get the latest css class

I would like to pull the last class from css rules using Regex in javascript.

The regex rule I'm going to do is start the search from the end of the rule, for example. to .myClass.myOtherClass' and return the first word after the last full stop - so the result will be ".myOtherClass"

Example css rules I need to map:

.myClass{color:red;} .myClass .myOtherClass{color:green;} #something .somethingElse{color:blue;} .something #myIdhere{color:purple;} #myId {color:black} .myClass1, .myClass2{colour:green} .myClass span{colour:purple} .myPseudo:after{} 

I can get the rules myself without {} info. Therefore, its regular expression will run each of the rules on its own. e.g. on '.myClass.myOtherClass' yourself. The conclusion from the rules above that I would like to get is that it matches, as shown below:

 .myClass .myOtherClass .somethingElse .something no match .myClass2 .myClass .myPseudo 

Can anyone help?

+5
source share
3 answers
 .*(\.[a-zA-Z0-9]*) 

extracting the first group gives you what you want for all your test cases.

This works thanks to greed .* , Which will match as much as possible, leaving the last class in line with the rest of the template.

Try here

+1
source

This RegEx will work for all valid CSS class names: ( Demo here )

 (\.-?[_a-zA-Z]+[_a-zA-Z0-9-]*) 

Here is the JavaScript to get all the css class names, as well as the last one: ( Demo here )

 var css = '' var classNames = css.match(/(\.-?[_a-zA-Z]+[_a-zA-Z0-9-]*)/g) var lastClass = classNames[classNames.length - 1] 

RegEx is partly taken from: fooobar.com/questions/8145 / ...

+1
source

Is this what you want?

 var str = 'your css'; var hits = str.match(/\.\w+/gm); var css = hits.pop(); //hits[hits.length-1]; 
0
source

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


All Articles