Reputation: 790
I have a long string that contains multiple css classes. With regex I would like to match every class name as I then need to replace these class names like so:
<span>CLASSNAME</span>
I have tried for hours to come up with a solution and I think I am close however for certain class names I am not able to exclude closing curly brackets from the match.
Here is a sample string I have been carrying out testing on:
#main .items-Outer p{ font-family:Verdana; color: #000000; font-size: 50px; font-weight: bold; }#footer .footer-inner p.intro{ font-family:Arial; color: #444444; font-size: 30; font-weight: normal; }.genericTxt{ font-family:Courier; color: #444444; font-size: 30; font-weight: normal; }
And here is the the regex I came up with so far:
((^(?:.+?)(?:[^{]*))|((?:\})(?:.+?)(?:[^{]*)))
Please look at the screenshot I am attaching as it will show more clearly the matches I get. My problem is that I would obviously like to exclude curly brackets from any match.
To clarify, example of matches I am after are:
Upvotes: 1
Views: 4515
Reputation: 17357
Assuming str contains your CSS, the following regex:
str.match(/(?:#\w+\s+)?\.[\w-]+(?:\s+\w+\s*\.\w+|\s+\w+)?/ig)
returns:
["#main .items-Outer p", "#footer .footer-inner p.intro", ".genericTxt"]
The regex is:
(?:#\w+\s+)? -- optional leading CSS id, i.e. #abc
\.[\w-]+ -- CSS classname, i.e. .ab-c
(?:
\s+\w+\s*\.\w+ -- optional CSS elt followed by classname, i.e. p.abc
| -- or
\s+\w+ -- optional CSS elt, i.e. p
)?
See demo
Upvotes: 0
Reputation: 30273
If and only if there won't be any nested curly braces, the following should work:
/\.(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?![^\{]*\})/
Here's a demo!
Note that I'm referencing this question for the valid-CSS-class-name regex.
EDIT
I just read your comment clarifying that you wish to match the entire selector, not just class names. In that case, try this, although I'm not as confident about its robustness:
/[^}]*(?=\{|$)/
Here's a demo of that one.
Upvotes: 2