2

I need to select all classes names in a css file, I am just new at it, also if someone can advice some good online tutorials for regex is appreciated.

Regex will be used in JavaScript

I came with this which works for simple classes: /(?<=\.).+?(?=\{)/g

.className { 
}

the above regex returned this: className

now I need to add for this too:

tagName1 {
}

#tagName2 {
}

.tagName3:hover {
}

.tagName4:anything {
}
should result in:
tagname1
tagname2
tagname3
tagname4

So how to select the above ones?

3
  • 1
    Do you have any examples of what should not match? Because from the only information you provided, this would work: (?<=\.|^|#)\w+(?=\s?{). You should also edit your question and include the language you are using. Commented Jul 4, 2019 at 0:45
  • 2
    I don't understand the last two examples. className is not a class name, it's a tag name. And #className is an ID, not a class name. What about more complex CSS selectors, like .classname:hover? Commented Jul 4, 2019 at 1:35
  • @Barmar, great, yes, I need to select tag names as well, and remove the :hover part or :(something) part Commented Jul 4, 2019 at 2:16

2 Answers 2

1

My guess is that, we would want to design an expression similar to,

([^:#\s.]+)(?:.*?)?\s*({[^}]*?})

where in this capturing group,

([^:#\s.]+)

we would deselect some chars such as ., # and space, and we'd collect our desired data.

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Great, also, to mark as correct answer, I just forgot to ask to add this: in case the class is: .className:hover you need to remove the :hover part, or any :something part
Looks good, also, can you please add an extra one for selecting as well the content of the class? everything inside the { xxxx } as well as the classnames and the { ? this is my last request haha
1

I'd use:

 ^[.#]?(\w+)(?=(?::\w+)?\s*{)

The wanted name is in group #1

Demo with javascript regex flavour.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.