DD
DevDash

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

InputResult
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

Want API access + no ads? Pro coming soon.