CSS Class from `class=""` Attribute in GO
Extract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.
Try it in the GO tester →Pattern
regexGO
class\s*=\s*["']([^"']+)["'] (flags: gi)Go (RE2) code
goGo
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.
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
—