XML Processing Instruction
Match XML processing instructions like `<?xml version="1.0" encoding="utf-8"?>` or `<?xml-stylesheet href="..."?>`.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("<\\?[\\w\\-]+(?:\\s+[\\w\\-]+\\s*=\\s*[\"'][^\"']*[\"'])*\\s*\\?>", "g");
const input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
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"<\\?[\\w\\-]+(?:\\s+[\\w\\-]+\\s*=\\s*[\"'][^\"']*[\"'])*\\s*\\?>")
input_text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
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(`<\?[\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.
Pattern
<\?[\w\-]+(?:\s+[\w\-]+\s*=\s*["'][^"']*["'])*\s*\?> (flags: g)Raw source: <\?[\w\-]+(?:\s+[\w\-]+\s*=\s*["'][^"']*["'])*\s*\?>
How it works
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
—Common use cases
- •XML/SVG/RSS preprocessing
- •Detecting and stripping XML declarations before merging documents
- •XSLT pipeline tooling
- •Sitemap and feed validation
Related patterns
XML Namespace Declaration
WebMatch XML namespace declarations (`xmlns="..."` and `xmlns:prefix="..."`), capturing the prefix and URI.
CSS Custom Property (Variable)
WebMatch CSS custom properties (variables) like `--brand-color` or `--font-size-lg`.
Cookie Header Value
WebParse name=value pairs from an HTTP `Cookie:` header value.
CSS Class from `class=""` Attribute
WebExtract the value of a `class="..."` attribute from raw HTML, handling double or single quotes.