Update: A beta version of XRegExp 0.3 is now available as part of the RegexPal download package.
JavaScript's regular expression flavor doesn't support named capture. Well, says who? XRegExp 0.2 brings named capture support, along with several other new features. But first of all, if you haven't seen the previous version, make sure to check out my post on XRegExp 0.1, because not all of the documentation is repeated below.
addFlags
method (New) Free-spacing and comments mode (x
) Dot matches all mode (s
) Several other minor improvements over v0.1 There are several different syntaxes in the wild for named capture. I've compiled the following table based on my understanding of the regex support of the libraries in question. XRegExp's syntax is included at the top.
Library | Capture | Back | In replacement | Stored at |
---|---|---|---|---|
XRegExp | (<name>…) | /k<name> | ${name} | result.name |
.NET | (?<name>…) (?'name'…) | /k<name> /k'name' | ${name} | Matcher. |
Perl 5.10 (beta) | (?<name>…) (?'name'…) | /k<name> /k'name' /g{name} | $+{name} | ?? |
Python |
| (?P=name) | /g<name> | result. |
PHP preg (PCRE) | (.NET, Perl, and Python styles) | $regs['name'] | $result['name'] |
No other major regex library currently supports named capture, although the JGsoft engine (used by products like RegexBuddy) supports both .NET and Python syntax. XRegExp does not use a question mark at the beginning of a named capturing group because that would prevent it from being used in regex literals (JavaScript would immediately throw an "invalid quantifier" error).
XRegExp supports named capture on an on-request basis. You can add named capture support to any regex though the use of the new "k
" flag. This is done for compatibility reasons and to ensure that regex compilation time remains as fast as possible in all situations.
Following are several examples of using named capture:
// Add named capture support using the XRegExp constructorvar repeatedWords = new XRegExp("//b (<word> //w+ ) //s+ //k<word> //b", "gixk");// Add named capture support using RegExp, after overriding the native constructorXRegExp.overrideNative();var repeatedWords = new RegExp("//b (<word> //w+ ) //s+ //k<word> //b", "gixk");// Add named capture support to a regex literalvar repeatedWords = //b (<word> /w+ ) /s+ /k<word> /b/.addFlags("gixk");var data = "The the test data.";// Check if data contains repeated wordsvar hasDuplicates = repeatedWords.test(data);// hasDuplicates: true// Use the regex to remove repeated wordsvar output = data.replace(repeatedWords, "${word}");// output: "The test data."
新闻热点
疑难解答
图片精选