XML Namespace Declaration in GO
Match XML namespace declarations (`xmlns="..."` and `xmlns:prefix="..."`), capturing the prefix and URI.
Try it in the GO tester →Pattern
regexGO
xmlns(?::([\w\-]+))?\s*=\s*["']([^"']+)["'] (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`xmlns(?::([\w\-]+))?\s*=\s*["']([^"']+)["']`)
input := `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`
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
xmlns matches the literal attribute name. (?::([\w\-]+))? optionally captures a colon-prefix (e.g. `xmlns:xlink`). \s*=\s* matches the equals with optional whitespace. ["']([^"']+)["'] captures the URI in either quote style.
Examples
Input
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">Matches
xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"
Input
<root xmlns='urn:custom'>Matches
xmlns='urn:custom'
Input
<plain>No match
—