XRegExp includes comprehensive support for named capture. Capture names can use the characters A–Z, a–z, 0–9, _, and $ only. Following are the details of XRegExp's named capture syntax:
(?<name>⋯)\k<name>${name}result.nameYou can compare these details to named capture in other regex flavors.
var repeatedWords = XRegExp("\\b (?<word>[a-z]+) \\s+ \\k<word> \\b", "gix");
var input = "The the test data.";
// Check if input contains repeated words
var hasRepeatedWords = repeatedWords.test(input); // -> true
// Use the regex to remove repeated words
var output = input.replace(repeatedWords, "${word}"); // -> "The test data."
var url = "http://yahoo.com/path/to/file?q=1";
var parser = XRegExp("^ (?<scheme> [^:/?]+ ) :// # aka protocol \n\
(?<host> [^/?]+ ) # domain name/IP \n\
(?<path> [^?]* ) \\?? # optional path \n\
(?<query> .* ) # optional query ", "x");
var parts = parser.exec(url);
/* ->
parts: ["http://yahoo.com/path/to/file?q=1", "http", "yahoo.com", "/path/to/file", "q=1"]
parts.scheme: "http"
parts.host: "yahoo.com"
parts.path: "/path/to/file"
parts.query: "q=1"
*/
// Named backreferences available in replacement functions as properties of the first argument
url = url.replace(parser, function (match) {
return match.replace(match.host, "microsoft.com");
});
// -> "http://microsoft.com/path/to/file?q=1"
lastMatch property of the global RegExp object or the RegExp.prototype.compile method, since those features were deprecated in JavaScript 1.5. Inline comments use the syntax (?#comment). They are an alternative to the line comments allowed in free-spacing mode.
var regex = XRegExp("(?#month)\\d\\d?[-/. ](?#day)\\d\\d?[-/. ](?#year)(?:\\d\\d){1,2}");
var isDate = regex.test("04/20/2008"); // -> true
TODO: Document me.