DD
DevDash

Regex for CSS ID Selector

Regex Pattern

^#[_a-zA-Z][_a-zA-Z0-9-]*$

CSS ID selector starting with #

Quick Answer

The regex pattern for css id selector is `^#[_a-zA-Z][_a-zA-Z0-9-]*$`. CSS ID selector starting with #. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
#header✓ Matches
#main-content✓ Matches
#_private✓ Matches
#123✗ No match
header✗ No match
.class✗ No match
# space✗ 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.