CSS Class from `class=""` Attribute in PY
Extract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.
Try it in the PY tester →Pattern
regexPY
class\s*=\s*["']([^"']+)["'] (flags: gi)Python (re) code
pyPython
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+.
How the pattern works
class\s*=\s* matches the attribute name with optional whitespace around the `=`. ["'] matches either quote style. ([^"']+) captures everything until the matching quote (the class list itself, possibly multiple classes). The closing ["'] matches the same quote style as opened — note this regex doesn't enforce that they MATCH, but in valid HTML they will.
Examples
Input
<div class="btn primary">Matches
class="btn primary"
Input
<span class='card'>Matches
class='card'
Input
<div id="foo">No match
—