XRegExp 0.2: Now With Named Capture_js面向对象_脚本之家

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.

HighlightsComprehensive named capture support Supports regex literals through the addFlags method Free-spacing and comments mode Dot matches all mode Several other minor improvements over v0.1 Named capture

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.




In replacement

Stored at

XRegExp`k${name}`.NET `k` `k'name'` `${name}Matcher.GroupsPerl 5.10 ``k`k'name' g{name} $+{name}??Python```gresult.groupPHP preg *(.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 \s+ \k \b", "gixk");// Add named capture support using RegExp, after overriding the native constructorXRegExp.overrideNative();var repeatedWords = new RegExp \s+ \k \b", "gixk");// Add named capture support to a regex literalvar repeatedWords = /b  s+ k b/.addFlags;var data = "The the test data.";// Check if data contains repeated wordsvar hasDuplicates = repeatedWords.test;// hasDuplicates: true// Use the regex to remove repeated wordsvar output = data.replace(repeatedWords, "${word}");// output: "The test data."

In the above code, I've also used the x flag provided by XRegExp, to improve readability. Note that the addFlags method can be called multiple times on the same regex (e.g., /pattern/g.addFlags), but I'd recommend adding all flags in one shot, for efficiency.

Here are a few more examples of using named capture, with an overly simplistic URL-matching regex (for comprehensive URL parsing, see parseUri):

var url = "";var urlParser = new XRegExp://\?;var parts = urlParser.exec;/* The result:parts.protocol: "http" ""parts.path: "/path/to/file"parts.query: "q=1" */// Named backreferences are also available in replace() callback functions as properties of the first argumentvar newUrl = url.replace(urlParser, function{return match.replace(, "");});// newUrl: ""

Note that XRegExp's named capture functionality does not support deprecated JavaScript features including the lastMatch property of the global RegExp object and the RegExp.prototype.compile() method.

Singleline modes

The other non-native flags XRegExp supports are s for "dot matches all" mode, and x for "free-spacing and comments" mode. For full details about these modifiers, see the FAQ in my XRegExp 0.1 post. However, one difference from the previous version is that XRegExp 0.2, when using the x flag, now allows whitespace between a regex token and its quantifier (quantifiers are, e.g., +, *?, or {1,3}). Although the previous version's handling/limitation in this regard was documented, it was atypical compared to other regex libraries. This has been fixed.

The code

/* XRegExp 0.2.2; MIT LicenseBy Steven Levithan ----------Adds support for the following regular expression features:- Free-spacing and comments - Dot matches all - Named capture  - Capture:  - Backreference: k - In replacement: ${name} - Stored at:*//* Protect this from running more than once, which would break its references to native functions */if (window.XRegExp === undefined) {var XRegExp; {var native = {RegExp: RegExp,exec: RegExp.prototype.exec,match: String.prototype.match,replace: String.prototype.replace};XRegExp = function  {return native.RegExp.addFlags;};RegExp.prototype.addFlags = function  {var pattern = this.source,useNamedCapture = false,re = XRegExp._re;flags =  +, /^[Ss]+//, "");if  > -1) {pattern =, re.extended, function  {return $1 ?  : $0;});}if  > -1) {var captureNames = [];pattern =, re.capturingGroup, function  {if  {if  useNamedCapture = true;captureNames.push;return "(";} else {return $0;}});if  {/* Replace named with numbered backreferences */pattern =, re.namedBackreference, function  {var index = $1 ? captureNames.indexOf : -1;return index > -1 ? "\" +  + " + $2 : "") : $0;});}}/* If "]" is the leading character in a character class, replace it with "]" for consistentcross-browser handling. This is needed to maintain correctness without the aid of browser sniffingwhen constructing the regexes which deal with character classes. They treat a leading "]" within acharacter class as a non-terminating, literal character, which is consistent with IE, .NET, Perl,PCRE, Python, Ruby, JGsoft, and most other regex engines. */pattern =, re.characterClass, function  {/* This second regex is only run when a leading "]" exists in the character class */return $1 ?]/, "$1\]") : $0;});if  > -1) {pattern =, re.singleline, function  {return $0 === "." ? "[\S\s]" : $0;});}var regex = native.RegExp(pattern,;if  {regex._captureNames = captureNames;/* Preserve capture names if adding flags to a regex which has already run through addFlags */} else if  {regex._captureNames = this._captureNames.valueOf();}return regex;};String.prototype.replace = function  {/* If search is not a regex which uses named capturing groups, just run the native replace method */if (!(search instanceof native.RegExp && search._captureNames)) {return native.replace.apply;}if (typeof replacement === "function") {return, search, function () {/* Convert arguments[0] from a string primitive to a string object which can store properties */arguments[0] = new String;/* Store named backreferences on the first argument before calling replacement */for (var i = 0; i < search._captureNames.length; i++) {if (search._captureNames[i]) arguments[0][search._captureNames[i]] = arguments[i + 1];}return replacement.apply;} else {return, search, function () {var args = arguments;return, XRegExp._re.replacementVariable, function  {/* Numbered backreference or special variable */if  {case "$": return "$";case "&": return args[0];case "`": return args[args.length - 1].substring(0, args[args.length - 2]);case "'": return args[args.length - 1].substring(args[args.length - 2] + args[0].length);/* Numbered backreference */default:/* What does "$10" mean?- Backreference 10, if at least 10 capturing groups exist- Backreference 1 followed by "0", if at least one capturing group exists- Else, it's the string "$10" */var literalNumbers = "";$1 = +$1; /* Cheap type-conversion */while ($1 > search._captureNames.length) {literalNumbers = $1.toString[0] + literalNumbers;$1 = Math.floor; /* Drop the last digit */}return  + literalNumbers;}/* Named backreference */} else if  {/* What does "${name}" mean?- Backreference to named capture "name", if it exists- Else, it's the string "${name}" */var index = search._captureNames.indexOf;return index > -1 ? args[index + 1] : $0;} else {return $0;}});});}};RegExp.prototype.exec = function  {var result =;if (!(this._captureNames && result && result.length > 1)) return result;for (var i = 1; i < result.length; i++) {var name = this._captureNames[i - 1];if  result[name] = result[i];}return result;};String.prototype.match = function  {if (!regexp._captureNames || return;return regexp.exec;}/* Regex syntax parsing with support for escapings, character classes, and various other context and cross-browser issues */XRegExp._re = {extended: /(?:[^[#s\]+|\|[^?]?(?:[^\]]+|\+|?/g,singleline: /(?:[^[\.]+|\|[^?]?(?:[^\]]+|\+|./g,characterClass: /(?:[^\[]+|\+|[^?(?:[^\]]+|\*]?/g,capturingGroup: /(?:[^[|[^?]?(?:[^\]]+|\*]?|+|?/g,namedBackreference: /(?:[^\[]+|\|[^?]?(?:[^\]]+|\*]?|\k+|\kYou can download it, or get the packed version .XRegExp has been tested in IE 5.5–7, Firefox, Opera 9.21, Safari 3.0.2 beta for Windows, and Swift 0.2.Finally, note that the XRE object from v0.1 has been removed. XRegExp now only creates one global variable: XRegExp. To permanently override the native RegExp constructor/object, you can now run XRegExp.overrideNative();
上一篇:jQuery学习——入门篇(附实例代码) 下一篇:没有了