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
| Input | Result |
|---|---|
| #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
JavaScript Variable Name
Valid JavaScript variable/identifier name
Python Variable Name
Valid Python identifier name
CSS Class Name
Valid CSS class name (starts with letter, underscore, or hyphen)
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