XRegExp 2.0 is coming soon. Get the Release Candidate at GitHub. See the list of changes in the Roadmap.

New syntax

Named capture

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:

You can compare these details to named capture in other regex flavors.

Example code

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"

Annotations

Inline comments

Inline comments use the syntax (?#comment). They are an alternative to the line comments allowed in free-spacing mode.

Example code

var regex = XRegExp("(?#month)\\d\\d?[-/. ](?#day)\\d\\d?[-/. ](?#year)(?:\\d\\d){1,2}");
var isDate = regex.test("04/20/2008"); // -> true

Annotations

Leading mode modifier

A mode modifier uses the syntax (?imsx)—where imsx is any combination of one or more of these allowed flags—and provides an alternative way to enable the specified flags. XRegExp allows the use of a mode modifier only at the very beginning of a pattern.

Example code

var regex = XRegExp("(?im)^[a-z]+$");
regex.ignoreCase; // -> true
regex.multiline; // -> true

function test (str, pattern) {
	return XRegExp(pattern).test(str);
}
test("Line1\nLine2", "(?sx)^ .+ $"); // -> true

Flags g (global) and y (sticky) cannot be set via a mode modifier.

Annotations