DD
DevDash

Regex for HTML Attribute

Regex Pattern

([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']

HTML attribute key-value pair (attr="value")

Quick Answer

The regex pattern for html attribute is `([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']`. HTML attribute key-value pair (attr="value"). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
class="my-class"✓ Matches
id="header"✓ Matches
data-value="123"✓ Matches
class✗ No match
="value"✗ No match
123="invalid"✗ No match

Code Examples

javascript

const regex = /([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']/;
const isValid = regex.test(value);

python

import re
pattern = r'([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/([a-zA-Z][a-zA-Z0-9-]*)\s*=\s*["']([^"']*)["']/', $value)) {
    echo "valid";
}

java

String pattern = "([a-zA-Z][a-zA-Z0-9-]*)\\s*=\\s*["']([^"']*)["']";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.