Regex to Match CSS Class Selectors
Match CSS class selectors in stylesheets with this regex. Identifies .class-name patterns in CSS code. Free online regex tester tool.
Regular Expression
/\.[a-zA-Z_-][a-zA-Z0-9_-]*/g
Token Breakdown
| Token | Description |
|---|---|
| \. | Matches a literal dot |
| [a-zA-Z_-] | Character class — matches any one of: a-zA-Z_- |
| [a-zA-Z0-9_-] | Character class — matches any one of: a-zA-Z0-9_- |
| * | Matches the preceding element zero or more times (greedy) |
Detailed Explanation
This regex matches CSS class selectors as they appear in stylesheets. Here is the token-by-token breakdown:
. — Matches a literal dot (period) character. In CSS, class selectors always begin with a dot followed by the class name. The backslash escapes the dot to prevent it from being interpreted as the regex wildcard metacharacter.
[a-zA-Z_-] — A character class matching the first character of the class name. CSS identifiers must begin with a letter (a-z or A-Z), an underscore (_), or a hyphen (-). In practice, starting with a hyphen has special meaning in CSS (vendor prefixes), but it is syntactically valid.
[a-zA-Z0-9_-]* — A character class matching the remaining characters of the class name. After the first character, digits (0-9) are also allowed. The * quantifier allows zero or more additional characters, so single-character class names like '.x' are valid.
The g flag enables global matching to find all class selectors in the CSS text. This pattern matches selectors like '.container', '.btn-primary', '.my_class', and '.-webkit-transform'. It is useful for extracting class names from CSS files, analyzing stylesheets, or building developer tools that work with CSS.
Note that this pattern matches class selectors in isolation. In complex CSS selectors like '.parent .child', each class would be matched separately. The pattern does not validate the entire CSS rule, only individual class selector tokens.
Example Test Strings
| Input | Expected |
|---|---|
| .container | Match |
| .btn-primary | Match |
| #main | No Match |
| .my_class123 | Match |
| .123invalid | No Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
26 charsFlags: gMatches: 3Ctrl+Shift+C to copy regex