Code
CSS class selector Regex
A CSS class selector is a dot followed by a class name. Valid class names may start with an optional hyphen, then must have a letter or underscore, and may continue with letters, digits, underscores and hyphens. This pattern checks one such selector on its own, which suits design system linters, tools that validate BEM names and editors that suggest selectors. Names that start with a digit are rejected because CSS requires them to be escaped. The pattern covers the ASCII subset only, does not accept escaped characters, and is not meant for compound selectors like .a.b or .btn:hover.
Pattern (JavaScript)
/^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$/Starts at the start of the line/string, then the character ".", then the character "-", optionally (zero or one time), then one of the characters _a-zA-Z, then one of the characters _a-zA-Z0-9-, zero or more times, then the end of the line/string.
Examples
Matches
- ✓ .btn
- ✓ .nav-item--active
- ✓ ._hidden
- ✓ .-webkit-thing
Does not match
- ✗ btn
- ✗ .2col
- ✗ .my class
- ✗ #id
Try it
0 matches (JavaScript engine)
.btn
.nav-item--active
._hidden
.-webkit-thing
btn
.2col
.my class
#idCode in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$/g;
const text = ".btn";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$')
text = '.btn'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$/';
$text = '.btn';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^\\.-?[_a-zA-Z][_a-zA-Z0-9-]*$");
String text = ".btn";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$`)
text := ".btn"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$");
var text = ".btn";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$").unwrap();
let text = ".btn";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^\.-?[_a-zA-Z][_a-zA-Z0-9-]*$/
text = '.btn'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Why is .2col rejected?
- CSS identifiers cannot start with a digit unless the digit is escaped, as in .\32 col. The pattern requires a letter or underscore after the optional hyphen to reflect that rule.
- Does it work for BEM class names?
- Yes. BEM uses double underscores and double hyphens, such as block__element--modifier, and both are allowed by the character class after the first letter.
- Can I use it to list all classes in a stylesheet?
- Remove the anchors, add the g flag and stop the name at a non-identifier character. Be aware that it may also match decimals like .5em, so filter out matches starting with a digit.
Related patterns
- C-style block comment/\*[\s\S]*?\*/
- CSS hex color code^#(?:[\da-fA-F]{3}){1,2}$|^#(?:[\da-fA-F]{4}){1,2}$
- Base64 encoded string^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)$
- Environment variable assignment (.env line)^(?:export\s+)?[A-Z_][A-Z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s#"']*)\s*(?:#.*)?$