XML Processing Instruction in GO
Match XML processing instructions like `<?xml version="1.0" encoding="utf-8"?>` or `<?xml-stylesheet href="..."?>`.
Try it in the GO tester →Pattern
regexGO
<\?[\w\-]+(?:\s+[\w\-]+\s*=\s*["'][^"']*["'])*\s*\?> (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`<\?[\w\-]+(?:\s+[\w\-]+\s*=\s*["'][^"']*["'])*\s*\?>`)
input := `<?xml version="1.0" encoding="UTF-8"?>`
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
<\? matches the literal opener. [\w\-]+ captures the PI target name. The repeating group matches optional `attr="value"` pairs. The trailing `\s*\?>` matches the closer. Works for the XML declaration and any custom processing instruction.
Examples
Input
<?xml version="1.0" encoding="UTF-8"?>Matches
<?xml version="1.0" encoding="UTF-8"?>
Input
<?xml-stylesheet type="text/xsl" href="style.xsl"?>Matches
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
Input
<root>plain</root>No match
—