3

By having a css file with css rules, I'd like to select only css class (i.e.) .tblGenFixed but not css values for a rule (i.e.) opacity: 0.3 .

This is my regex: /(\.([\w_]+))/g

This is my alternative solution but it doesn't work /(?!\{)(\.([\w_]+))(?!\})/g

I have set an example in regex101 here https://regex101.com/r/gG4nN4/1

How can I ignore css rule values ?

3
  • How about this? ----> regex101.com/r/gG4nN4/3 Commented Jan 13, 2015 at 18:24
  • 1
    it works for classes, but I cannot rely on spaces before a class, what if I have a rule for two classes ? see my update regex101.com/r/gG4nN4/4 Commented Jan 13, 2015 at 18:27
  • Here is another one. Commented Jan 13, 2015 at 18:42

2 Answers 2

5

See this : Which characters are valid in CSS class names/selectors?

A value will have a digit after the dot. Luckily, valid CSS class names cannot start with a digit :)

Your regexp has to match a dot first, then a letter or - or _

! if you look for whitespace before the dot, a value like .5 will match ...

Try this one : (\.([a-zA-Z_-]{1}[\w-_]+))

Edit :

See this too : Regex to match a CSS class name

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

Relevant quote :

Basically, a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must be a letter or underscore, and the name must be at least 2 characters long.

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

Comments

2

Depending on how your CSS is written, you might be able to get what you are looking for by requiring whitespace before the period:

 \W/(\.([\w_]+))/g

Here's a fork of your regex.

Depending on what you are looking for, you might want to skip one of those capture groups:

\W\.([\w_]+)

I'd also warn against parsing CSS with a regex without manually examining the results.

1 Comment

\w also includes _ in its character set, but not -, a valid character for CSS classes.

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.