Regex for CSS Class Name
Regex Pattern
^-?[_a-zA-Z][_a-zA-Z0-9-]*$Valid CSS class name (starts with letter, underscore, or hyphen)
Quick Answer
The regex pattern for css class name is `^-?[_a-zA-Z][_a-zA-Z0-9-]*$`. Valid CSS class name (starts with letter, underscore, or hyphen). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| my-class | ✓ Matches |
| _hidden | ✓ Matches |
| btn-primary | ✓ Matches |
| -moz-appearance | ✓ Matches |
| 123class | ✗ No match |
| .class | ✗ No match |
| #id | ✗ No match |
| my class | ✗ No match |
Code Examples
javascript
const regex = /^-?[_a-zA-Z][_a-zA-Z0-9-]*$/; const isValid = regex.test(value);
python
import re
pattern = r'^-?[_a-zA-Z][_a-zA-Z0-9-]*$'
if re.match(pattern, value):
print("valid")ruby
pattern = /^-?[_a-zA-Z][_a-zA-Z0-9-]*$/ if value =~ pattern puts "valid" end
php
if (preg_match('/^-?[_a-zA-Z][_a-zA-Z0-9-]*$/', $value)) {
echo "valid";
}java
String pattern = "^-?[_a-zA-Z][_a-zA-Z0-9-]*$"; boolean isValid = value.matches(pattern);
Frequently Asked Questions
Related Regex Patterns
JavaScript Variable Name
Valid JavaScript variable/identifier name
Python Variable Name
Valid Python identifier name
CSS ID Selector
CSS ID selector starting with #
JSON Key
JSON object key (quoted string followed by colon)
Semantic Version (Strict)
Strict semantic versioning (MAJOR.MINOR.PATCH)
SemVer with Pre-release
Full semantic version with optional pre-release and build metadata