XML Namespace Declaration in PY
Match XML namespace declarations (`xmlns="..."` and `xmlns:prefix="..."`), capturing the prefix and URI.
Try it in the PY tester →Pattern
regexPY
xmlns(?::([\w\-]+))?\s*=\s*["']([^"']+)["'] (flags: g)Python (re) code
pyPython
import re
pattern = re.compile(r"xmlns(?::([\\w\\-]+))?\\s*=\\s*[\"']([^\"']+)[\"']")
input_text = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
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
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
—