CSS Class from `class=""` Attribute
Extract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("class\\s*=\\s*[\"']([^\"']+)[\"']", "gi");
const input = "<div class=\"btn primary\">";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"class\\s*=\\s*[\"']([^\"']+)[\"']", re.IGNORECASE)
input_text = "<div class=\"btn primary\">"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?i)class\s*=\s*["']([^"']+)["']`)
input := `<div class="btn primary">`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
class\s*=\s*["']([^"']+)["'] (flags: gi)Raw source: class\s*=\s*["']([^"']+)["']
How it works
Examples
Input
<div class="btn primary">Matches
class="btn primary"
Input
<span class='card'>Matches
class='card'
Input
<div id="foo">No match
—Common use cases
- •HTML scraping and class auditing
- •Migrating CSS classes during refactors
- •Bundler / lint tooling that reports unused classes
- •Generating component manifests from JSX/HTML
Related patterns
HTML Attribute
WebMatch HTML attributes of the form name="value" or name='value' and capture both parts.
Cookie Header Value
WebParse name=value pairs from an HTTP `Cookie:` header value.
CSS Custom Property (Variable)
WebMatch CSS custom properties (variables) like `--brand-color` or `--font-size-lg`.
CSS hsl() / hsla() Color
WebMatch CSS hsl() and hsla() color functions, capturing hue (0–360), saturation, lightness, and optional alpha.