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 ?

alexserver
  • 1,248
  • 2
  • 15
  • 30

2 Answers2

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.

Community
  • 1
  • 1
sodawillow
  • 10,435
  • 3
  • 31
  • 41
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.

Jon Ericson
  • 19,534
  • 11
  • 93
  • 140
  • 1
    `\w` also includes `_` in its character set, but not `-`, a valid character for CSS classes. – Sean Dec 15 '15 at 09:02