XML regex

XML

XML stands for Extensible Markup Language and is used for storing arbitrary data. Usually, it’s not a good thing to parse XML with regular expressions, but in certain situations, it can be very helpful to retrieve (scrape) a specific piece of information that you need.

Extract value between XML tags

One of the most common operations with XML and regex is the extraction of the text between certain tags (a.k.a. scraping). For this operation, the following regular expression can be used.

/(?<=<TAG.*?>)(.*?)(?=<\/TAG>)/g

Test it!
/(?<=<TAG.*?>)(.*?)(?=<\/TAG>)/g

True

False

Enter a text in the input above to see the result

Example code in Javascript:

// Extract text between <from> tag
var xmlRegexG = /(?<=<from.*?>)(.*?)(?=<\/from>)/g;
'<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don\'t forget me this weekend!</body></note>'.match(xmlRegexG); // returns ['Jani'];

Test it!

True

False

Enter a text in the input above to see the result

Test it!

True

False

Enter a text in the input above to see the result

Notes on regex XML extraction

While this extraction might be a good option in some cases, usually it’s better to use specific XML parsers for such tasks. In such case, once XML is validated and parsed, the required information can be retrieved using Document queries. For instance, in browser version of JavaScript there’s a specified DomParser class for these cases:

var text = "<bookstore><book><title>Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year></book></bookstore>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text,"text/xml");

var demoContent = xmlDoc.getElementsByTagName('author')[0].innerHTML; // Giada De Laurentiis