xregexp.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  1. /*!
  2. * XRegExp 3.1.0
  3. * <xregexp.com>
  4. * Steven Levithan (c) 2007-2016 MIT License
  5. */
  6. /**
  7. * XRegExp provides augmented, extensible regular expressions. You get additional regex syntax and
  8. * flags, beyond what browsers support natively. XRegExp is also a regex utility belt with tools to
  9. * make your client-side grepping simpler and more powerful, while freeing you from related
  10. * cross-browser inconsistencies.
  11. */
  12. 'use strict';
  13. /* ==============================
  14. * Private stuff
  15. * ============================== */
  16. // Property name used for extended regex instance data
  17. var REGEX_DATA = 'xregexp';
  18. // Optional features that can be installed and uninstalled
  19. var features = {
  20. astral: false,
  21. natives: false
  22. };
  23. // Native methods to use and restore ('native' is an ES3 reserved keyword)
  24. var nativ = {
  25. exec: RegExp.prototype.exec,
  26. test: RegExp.prototype.test,
  27. match: String.prototype.match,
  28. replace: String.prototype.replace,
  29. split: String.prototype.split
  30. };
  31. // Storage for fixed/extended native methods
  32. var fixed = {};
  33. // Storage for regexes cached by `XRegExp.cache`
  34. var regexCache = {};
  35. // Storage for pattern details cached by the `XRegExp` constructor
  36. var patternCache = {};
  37. // Storage for regex syntax tokens added internally or by `XRegExp.addToken`
  38. var tokens = [];
  39. // Token scopes
  40. var defaultScope = 'default';
  41. var classScope = 'class';
  42. // Regexes that match native regex syntax, including octals
  43. var nativeTokens = {
  44. // Any native multicharacter token in default scope, or any single character
  45. 'default': /\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u(?:[\dA-Fa-f]{4}|{[\dA-Fa-f]+})|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??|[\s\S]/,
  46. // Any native multicharacter token in character class scope, or any single character
  47. 'class': /\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u(?:[\dA-Fa-f]{4}|{[\dA-Fa-f]+})|c[A-Za-z]|[\s\S])|[\s\S]/
  48. };
  49. // Any backreference or dollar-prefixed character in replacement strings
  50. var replacementToken = /\$(?:{([\w$]+)}|(\d\d?|[\s\S]))/g;
  51. // Check for correct `exec` handling of nonparticipating capturing groups
  52. var correctExecNpcg = nativ.exec.call(/()??/, '')[1] === undefined;
  53. // Check for ES6 `flags` prop support
  54. var hasFlagsProp = /x/.flags !== undefined;
  55. // Shortcut to `Object.prototype.toString`
  56. var toString = {}.toString;
  57. function hasNativeFlag(flag) {
  58. // Can't check based on the presense of properties/getters since
  59. // browsers might support such properties even when don't support the
  60. // corresponding flag in regex construction (tested in Chrome 48, where
  61. // `'unicode' in /x/` is true but trying to construct a regex with flag
  62. // `u` throws an error).
  63. var isSupported = true;
  64. try {
  65. new RegExp('', flag);
  66. } catch (exception) {
  67. isSupported = false;
  68. }
  69. return isSupported;
  70. }
  71. // Check for ES6 `u` flag support
  72. var hasNativeU = hasNativeFlag('u');
  73. // Check for ES6 `y` flag support
  74. var hasNativeY = hasNativeFlag('y');
  75. // Tracker for known flags, including addon flags
  76. var registeredFlags = {
  77. g: true,
  78. i: true,
  79. m: true,
  80. u: hasNativeU,
  81. y: hasNativeY
  82. };
  83. /**
  84. * Attaches extended data and `XRegExp.prototype` properties to a regex object.
  85. *
  86. * @private
  87. * @param {RegExp} regex Regex to augment.
  88. * @param {Array} captureNames Array with capture names, or `null`.
  89. * @param {String} xSource XRegExp pattern used to generate `regex`, or `null` if N/A.
  90. * @param {String} xFlags XRegExp flags used to generate `regex`, or `null` if N/A.
  91. * @param {Boolean} [isInternalOnly=false] Whether the regex will be used only for internal
  92. * operations, and never exposed to users. For internal-only regexes, we can improve perf by
  93. * skipping some operations like attaching `XRegExp.prototype` properties.
  94. * @returns {RegExp} Augmented regex.
  95. */
  96. function augment(regex, captureNames, xSource, xFlags, isInternalOnly) {
  97. var p;
  98. regex[REGEX_DATA] = {
  99. captureNames: captureNames
  100. };
  101. if (isInternalOnly) {
  102. return regex;
  103. }
  104. // Can't auto-inherit these since the XRegExp constructor returns a nonprimitive value
  105. if (regex.__proto__) {
  106. regex.__proto__ = XRegExp.prototype;
  107. } else {
  108. for (p in XRegExp.prototype) {
  109. // An `XRegExp.prototype.hasOwnProperty(p)` check wouldn't be worth it here, since
  110. // this is performance sensitive, and enumerable `Object.prototype` or
  111. // `RegExp.prototype` extensions exist on `regex.prototype` anyway
  112. regex[p] = XRegExp.prototype[p];
  113. }
  114. }
  115. regex[REGEX_DATA].source = xSource;
  116. // Emulate the ES6 `flags` prop by ensuring flags are in alphabetical order
  117. regex[REGEX_DATA].flags = xFlags ? xFlags.split('').sort().join('') : xFlags;
  118. return regex;
  119. }
  120. /**
  121. * Removes any duplicate characters from the provided string.
  122. *
  123. * @private
  124. * @param {String} str String to remove duplicate characters from.
  125. * @returns {String} String with any duplicate characters removed.
  126. */
  127. function clipDuplicates(str) {
  128. return nativ.replace.call(str, /([\s\S])(?=[\s\S]*\1)/g, '');
  129. }
  130. /**
  131. * Copies a regex object while preserving extended data and augmenting with `XRegExp.prototype`
  132. * properties. The copy has a fresh `lastIndex` property (set to zero). Allows adding and removing
  133. * flags g and y while copying the regex.
  134. *
  135. * @private
  136. * @param {RegExp} regex Regex to copy.
  137. * @param {Object} [options] Options object with optional properties:
  138. * <li>`addG` {Boolean} Add flag g while copying the regex.
  139. * <li>`addY` {Boolean} Add flag y while copying the regex.
  140. * <li>`removeG` {Boolean} Remove flag g while copying the regex.
  141. * <li>`removeY` {Boolean} Remove flag y while copying the regex.
  142. * <li>`isInternalOnly` {Boolean} Whether the copied regex will be used only for internal
  143. * operations, and never exposed to users. For internal-only regexes, we can improve perf by
  144. * skipping some operations like attaching `XRegExp.prototype` properties.
  145. * @returns {RegExp} Copy of the provided regex, possibly with modified flags.
  146. */
  147. function copyRegex(regex, options) {
  148. if (!XRegExp.isRegExp(regex)) {
  149. throw new TypeError('Type RegExp expected');
  150. }
  151. var xData = regex[REGEX_DATA] || {},
  152. flags = getNativeFlags(regex),
  153. flagsToAdd = '',
  154. flagsToRemove = '',
  155. xregexpSource = null,
  156. xregexpFlags = null;
  157. options = options || {};
  158. if (options.removeG) {flagsToRemove += 'g';}
  159. if (options.removeY) {flagsToRemove += 'y';}
  160. if (flagsToRemove) {
  161. flags = nativ.replace.call(flags, new RegExp('[' + flagsToRemove + ']+', 'g'), '');
  162. }
  163. if (options.addG) {flagsToAdd += 'g';}
  164. if (options.addY) {flagsToAdd += 'y';}
  165. if (flagsToAdd) {
  166. flags = clipDuplicates(flags + flagsToAdd);
  167. }
  168. if (!options.isInternalOnly) {
  169. if (xData.source !== undefined) {
  170. xregexpSource = xData.source;
  171. }
  172. // null or undefined; don't want to add to `flags` if the previous value was null, since
  173. // that indicates we're not tracking original precompilation flags
  174. if (xData.flags != null) {
  175. // Flags are only added for non-internal regexes by `XRegExp.globalize`. Flags are
  176. // never removed for non-internal regexes, so don't need to handle it
  177. xregexpFlags = flagsToAdd ? clipDuplicates(xData.flags + flagsToAdd) : xData.flags;
  178. }
  179. }
  180. // Augment with `XRegExp.prototype` properties, but use the native `RegExp` constructor to
  181. // avoid searching for special tokens. That would be wrong for regexes constructed by
  182. // `RegExp`, and unnecessary for regexes constructed by `XRegExp` because the regex has
  183. // already undergone the translation to native regex syntax
  184. regex = augment(
  185. new RegExp(regex.source, flags),
  186. hasNamedCapture(regex) ? xData.captureNames.slice(0) : null,
  187. xregexpSource,
  188. xregexpFlags,
  189. options.isInternalOnly
  190. );
  191. return regex;
  192. }
  193. /**
  194. * Converts hexadecimal to decimal.
  195. *
  196. * @private
  197. * @param {String} hex
  198. * @returns {Number}
  199. */
  200. function dec(hex) {
  201. return parseInt(hex, 16);
  202. }
  203. /**
  204. * Returns native `RegExp` flags used by a regex object.
  205. *
  206. * @private
  207. * @param {RegExp} regex Regex to check.
  208. * @returns {String} Native flags in use.
  209. */
  210. function getNativeFlags(regex) {
  211. return hasFlagsProp ?
  212. regex.flags :
  213. // Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or
  214. // concatenation with an empty string) allows this to continue working predictably when
  215. // `XRegExp.proptotype.toString` is overriden
  216. nativ.exec.call(/\/([a-z]*)$/i, RegExp.prototype.toString.call(regex))[1];
  217. }
  218. /**
  219. * Determines whether a regex has extended instance data used to track capture names.
  220. *
  221. * @private
  222. * @param {RegExp} regex Regex to check.
  223. * @returns {Boolean} Whether the regex uses named capture.
  224. */
  225. function hasNamedCapture(regex) {
  226. return !!(regex[REGEX_DATA] && regex[REGEX_DATA].captureNames);
  227. }
  228. /**
  229. * Converts decimal to hexadecimal.
  230. *
  231. * @private
  232. * @param {Number|String} dec
  233. * @returns {String}
  234. */
  235. function hex(dec) {
  236. return parseInt(dec, 10).toString(16);
  237. }
  238. /**
  239. * Returns the first index at which a given value can be found in an array.
  240. *
  241. * @private
  242. * @param {Array} array Array to search.
  243. * @param {*} value Value to locate in the array.
  244. * @returns {Number} Zero-based index at which the item is found, or -1.
  245. */
  246. function indexOf(array, value) {
  247. var len = array.length, i;
  248. for (i = 0; i < len; ++i) {
  249. if (array[i] === value) {
  250. return i;
  251. }
  252. }
  253. return -1;
  254. }
  255. /**
  256. * Determines whether a value is of the specified type, by resolving its internal [[Class]].
  257. *
  258. * @private
  259. * @param {*} value Object to check.
  260. * @param {String} type Type to check for, in TitleCase.
  261. * @returns {Boolean} Whether the object matches the type.
  262. */
  263. function isType(value, type) {
  264. return toString.call(value) === '[object ' + type + ']';
  265. }
  266. /**
  267. * Checks whether the next nonignorable token after the specified position is a quantifier.
  268. *
  269. * @private
  270. * @param {String} pattern Pattern to search within.
  271. * @param {Number} pos Index in `pattern` to search at.
  272. * @param {String} flags Flags used by the pattern.
  273. * @returns {Boolean} Whether the next token is a quantifier.
  274. */
  275. function isQuantifierNext(pattern, pos, flags) {
  276. return nativ.test.call(
  277. flags.indexOf('x') > -1 ?
  278. // Ignore any leading whitespace, line comments, and inline comments
  279. /^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/ :
  280. // Ignore any leading inline comments
  281. /^(?:\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/,
  282. pattern.slice(pos)
  283. );
  284. }
  285. /**
  286. * Pads the provided string with as many leading zeros as needed to get to length 4. Used to produce
  287. * fixed-length hexadecimal values.
  288. *
  289. * @private
  290. * @param {String} str
  291. * @returns {String}
  292. */
  293. function pad4(str) {
  294. while (str.length < 4) {
  295. str = '0' + str;
  296. }
  297. return str;
  298. }
  299. /**
  300. * Checks for flag-related errors, and strips/applies flags in a leading mode modifier. Offloads
  301. * the flag preparation logic from the `XRegExp` constructor.
  302. *
  303. * @private
  304. * @param {String} pattern Regex pattern, possibly with a leading mode modifier.
  305. * @param {String} flags Any combination of flags.
  306. * @returns {Object} Object with properties `pattern` and `flags`.
  307. */
  308. function prepareFlags(pattern, flags) {
  309. var i;
  310. // Recent browsers throw on duplicate flags, so copy this behavior for nonnative flags
  311. if (clipDuplicates(flags) !== flags) {
  312. throw new SyntaxError('Invalid duplicate regex flag ' + flags);
  313. }
  314. // Strip and apply a leading mode modifier with any combination of flags except g or y
  315. pattern = nativ.replace.call(pattern, /^\(\?([\w$]+)\)/, function($0, $1) {
  316. if (nativ.test.call(/[gy]/, $1)) {
  317. throw new SyntaxError('Cannot use flag g or y in mode modifier ' + $0);
  318. }
  319. // Allow duplicate flags within the mode modifier
  320. flags = clipDuplicates(flags + $1);
  321. return '';
  322. });
  323. // Throw on unknown native or nonnative flags
  324. for (i = 0; i < flags.length; ++i) {
  325. if (!registeredFlags[flags.charAt(i)]) {
  326. throw new SyntaxError('Unknown regex flag ' + flags.charAt(i));
  327. }
  328. }
  329. return {
  330. pattern: pattern,
  331. flags: flags
  332. };
  333. }
  334. /**
  335. * Prepares an options object from the given value.
  336. *
  337. * @private
  338. * @param {String|Object} value Value to convert to an options object.
  339. * @returns {Object} Options object.
  340. */
  341. function prepareOptions(value) {
  342. var options = {};
  343. if (isType(value, 'String')) {
  344. XRegExp.forEach(value, /[^\s,]+/, function(match) {
  345. options[match] = true;
  346. });
  347. return options;
  348. }
  349. return value;
  350. }
  351. /**
  352. * Registers a flag so it doesn't throw an 'unknown flag' error.
  353. *
  354. * @private
  355. * @param {String} flag Single-character flag to register.
  356. */
  357. function registerFlag(flag) {
  358. if (!/^[\w$]$/.test(flag)) {
  359. throw new Error('Flag must be a single character A-Za-z0-9_$');
  360. }
  361. registeredFlags[flag] = true;
  362. }
  363. /**
  364. * Runs built-in and custom regex syntax tokens in reverse insertion order at the specified
  365. * position, until a match is found.
  366. *
  367. * @private
  368. * @param {String} pattern Original pattern from which an XRegExp object is being built.
  369. * @param {String} flags Flags being used to construct the regex.
  370. * @param {Number} pos Position to search for tokens within `pattern`.
  371. * @param {Number} scope Regex scope to apply: 'default' or 'class'.
  372. * @param {Object} context Context object to use for token handler functions.
  373. * @returns {Object} Object with properties `matchLength`, `output`, and `reparse`; or `null`.
  374. */
  375. function runTokens(pattern, flags, pos, scope, context) {
  376. var i = tokens.length,
  377. leadChar = pattern.charAt(pos),
  378. result = null,
  379. match,
  380. t;
  381. // Run in reverse insertion order
  382. while (i--) {
  383. t = tokens[i];
  384. if (
  385. (t.leadChar && t.leadChar !== leadChar) ||
  386. (t.scope !== scope && t.scope !== 'all') ||
  387. (t.flag && flags.indexOf(t.flag) === -1)
  388. ) {
  389. continue;
  390. }
  391. match = XRegExp.exec(pattern, t.regex, pos, 'sticky');
  392. if (match) {
  393. result = {
  394. matchLength: match[0].length,
  395. output: t.handler.call(context, match, scope, flags),
  396. reparse: t.reparse
  397. };
  398. // Finished with token tests
  399. break;
  400. }
  401. }
  402. return result;
  403. }
  404. /**
  405. * Enables or disables implicit astral mode opt-in. When enabled, flag A is automatically added to
  406. * all new regexes created by XRegExp. This causes an error to be thrown when creating regexes if
  407. * the Unicode Base addon is not available, since flag A is registered by that addon.
  408. *
  409. * @private
  410. * @param {Boolean} on `true` to enable; `false` to disable.
  411. */
  412. function setAstral(on) {
  413. features.astral = on;
  414. }
  415. /**
  416. * Enables or disables native method overrides.
  417. *
  418. * @private
  419. * @param {Boolean} on `true` to enable; `false` to disable.
  420. */
  421. function setNatives(on) {
  422. RegExp.prototype.exec = (on ? fixed : nativ).exec;
  423. RegExp.prototype.test = (on ? fixed : nativ).test;
  424. String.prototype.match = (on ? fixed : nativ).match;
  425. String.prototype.replace = (on ? fixed : nativ).replace;
  426. String.prototype.split = (on ? fixed : nativ).split;
  427. features.natives = on;
  428. }
  429. /**
  430. * Returns the object, or throws an error if it is `null` or `undefined`. This is used to follow
  431. * the ES5 abstract operation `ToObject`.
  432. *
  433. * @private
  434. * @param {*} value Object to check and return.
  435. * @returns {*} The provided object.
  436. */
  437. function toObject(value) {
  438. // null or undefined
  439. if (value == null) {
  440. throw new TypeError('Cannot convert null or undefined to object');
  441. }
  442. return value;
  443. }
  444. /* ==============================
  445. * Constructor
  446. * ============================== */
  447. /**
  448. * Creates an extended regular expression object for matching text with a pattern. Differs from a
  449. * native regular expression in that additional syntax and flags are supported. The returned object
  450. * is in fact a native `RegExp` and works with all native methods.
  451. *
  452. * @class XRegExp
  453. * @constructor
  454. * @param {String|RegExp} pattern Regex pattern string, or an existing regex object to copy.
  455. * @param {String} [flags] Any combination of flags.
  456. * Native flags:
  457. * <li>`g` - global
  458. * <li>`i` - ignore case
  459. * <li>`m` - multiline anchors
  460. * <li>`u` - unicode (ES6)
  461. * <li>`y` - sticky (Firefox 3+, ES6)
  462. * Additional XRegExp flags:
  463. * <li>`n` - explicit capture
  464. * <li>`s` - dot matches all (aka singleline)
  465. * <li>`x` - free-spacing and line comments (aka extended)
  466. * <li>`A` - astral (requires the Unicode Base addon)
  467. * Flags cannot be provided when constructing one `RegExp` from another.
  468. * @returns {RegExp} Extended regular expression object.
  469. * @example
  470. *
  471. * // With named capture and flag x
  472. * XRegExp('(?<year> [0-9]{4} ) -? # year \n\
  473. * (?<month> [0-9]{2} ) -? # month \n\
  474. * (?<day> [0-9]{2} ) # day ', 'x');
  475. *
  476. * // Providing a regex object copies it. Native regexes are recompiled using native (not XRegExp)
  477. * // syntax. Copies maintain extended data, are augmented with `XRegExp.prototype` properties, and
  478. * // have fresh `lastIndex` properties (set to zero).
  479. * XRegExp(/regex/);
  480. */
  481. function XRegExp(pattern, flags) {
  482. var context = {
  483. hasNamedCapture: false,
  484. captureNames: []
  485. },
  486. scope = defaultScope,
  487. output = '',
  488. pos = 0,
  489. result,
  490. token,
  491. generated,
  492. appliedPattern,
  493. appliedFlags;
  494. if (XRegExp.isRegExp(pattern)) {
  495. if (flags !== undefined) {
  496. throw new TypeError('Cannot supply flags when copying a RegExp');
  497. }
  498. return copyRegex(pattern);
  499. }
  500. // Copy the argument behavior of `RegExp`
  501. pattern = pattern === undefined ? '' : String(pattern);
  502. flags = flags === undefined ? '' : String(flags);
  503. if (XRegExp.isInstalled('astral') && flags.indexOf('A') === -1) {
  504. // This causes an error to be thrown if the Unicode Base addon is not available
  505. flags += 'A';
  506. }
  507. if (!patternCache[pattern]) {
  508. patternCache[pattern] = {};
  509. }
  510. if (!patternCache[pattern][flags]) {
  511. // Check for flag-related errors, and strip/apply flags in a leading mode modifier
  512. result = prepareFlags(pattern, flags);
  513. appliedPattern = result.pattern;
  514. appliedFlags = result.flags;
  515. // Use XRegExp's tokens to translate the pattern to a native regex pattern.
  516. // `appliedPattern.length` may change on each iteration if tokens use `reparse`
  517. while (pos < appliedPattern.length) {
  518. do {
  519. // Check for custom tokens at the current position
  520. result = runTokens(appliedPattern, appliedFlags, pos, scope, context);
  521. // If the matched token used the `reparse` option, splice its output into the
  522. // pattern before running tokens again at the same position
  523. if (result && result.reparse) {
  524. appliedPattern = appliedPattern.slice(0, pos) +
  525. result.output +
  526. appliedPattern.slice(pos + result.matchLength);
  527. }
  528. } while (result && result.reparse);
  529. if (result) {
  530. output += result.output;
  531. pos += (result.matchLength || 1);
  532. } else {
  533. // Get the native token at the current position
  534. token = XRegExp.exec(appliedPattern, nativeTokens[scope], pos, 'sticky')[0];
  535. output += token;
  536. pos += token.length;
  537. if (token === '[' && scope === defaultScope) {
  538. scope = classScope;
  539. } else if (token === ']' && scope === classScope) {
  540. scope = defaultScope;
  541. }
  542. }
  543. }
  544. patternCache[pattern][flags] = {
  545. pattern: output,
  546. // Strip all but native flags
  547. flags: nativ.replace.call(appliedFlags, /[^gimuy]+/g, ''),
  548. // `context.captureNames` has an item for each capturing group, even if unnamed
  549. captures: context.hasNamedCapture ? context.captureNames : null
  550. };
  551. }
  552. generated = patternCache[pattern][flags];
  553. return augment(
  554. new RegExp(generated.pattern, generated.flags),
  555. generated.captures,
  556. pattern,
  557. flags
  558. );
  559. };
  560. // Add `RegExp.prototype` to the prototype chain
  561. XRegExp.prototype = new RegExp();
  562. /* ==============================
  563. * Public properties
  564. * ============================== */
  565. /**
  566. * The XRegExp version number as a string containing three dot-separated parts. For example,
  567. * '2.0.0-beta-3'.
  568. *
  569. * @static
  570. * @memberOf XRegExp
  571. * @type String
  572. */
  573. XRegExp.version = '3.1.0';
  574. /* ==============================
  575. * Public methods
  576. * ============================== */
  577. // Intentionally undocumented
  578. XRegExp._hasNativeFlag = hasNativeFlag;
  579. /**
  580. * Extends XRegExp syntax and allows custom flags. This is used internally and can be used to
  581. * create XRegExp addons. If more than one token can match the same string, the last added wins.
  582. *
  583. * @memberOf XRegExp
  584. * @param {RegExp} regex Regex object that matches the new token.
  585. * @param {Function} handler Function that returns a new pattern string (using native regex syntax)
  586. * to replace the matched token within all future XRegExp regexes. Has access to persistent
  587. * properties of the regex being built, through `this`. Invoked with three arguments:
  588. * <li>The match array, with named backreference properties.
  589. * <li>The regex scope where the match was found: 'default' or 'class'.
  590. * <li>The flags used by the regex, including any flags in a leading mode modifier.
  591. * The handler function becomes part of the XRegExp construction process, so be careful not to
  592. * construct XRegExps within the function or you will trigger infinite recursion.
  593. * @param {Object} [options] Options object with optional properties:
  594. * <li>`scope` {String} Scope where the token applies: 'default', 'class', or 'all'.
  595. * <li>`flag` {String} Single-character flag that triggers the token. This also registers the
  596. * flag, which prevents XRegExp from throwing an 'unknown flag' error when the flag is used.
  597. * <li>`optionalFlags` {String} Any custom flags checked for within the token `handler` that are
  598. * not required to trigger the token. This registers the flags, to prevent XRegExp from
  599. * throwing an 'unknown flag' error when any of the flags are used.
  600. * <li>`reparse` {Boolean} Whether the `handler` function's output should not be treated as
  601. * final, and instead be reparseable by other tokens (including the current token). Allows
  602. * token chaining or deferring.
  603. * <li>`leadChar` {String} Single character that occurs at the beginning of any successful match
  604. * of the token (not always applicable). This doesn't change the behavior of the token unless
  605. * you provide an erroneous value. However, providing it can increase the token's performance
  606. * since the token can be skipped at any positions where this character doesn't appear.
  607. * @example
  608. *
  609. * // Basic usage: Add \a for the ALERT control code
  610. * XRegExp.addToken(
  611. * /\\a/,
  612. * function() {return '\\x07';},
  613. * {scope: 'all'}
  614. * );
  615. * XRegExp('\\a[\\a-\\n]+').test('\x07\n\x07'); // -> true
  616. *
  617. * // Add the U (ungreedy) flag from PCRE and RE2, which reverses greedy and lazy quantifiers.
  618. * // Since `scope` is not specified, it uses 'default' (i.e., transformations apply outside of
  619. * // character classes only)
  620. * XRegExp.addToken(
  621. * /([?*+]|{\d+(?:,\d*)?})(\??)/,
  622. * function(match) {return match[1] + (match[2] ? '' : '?');},
  623. * {flag: 'U'}
  624. * );
  625. * XRegExp('a+', 'U').exec('aaa')[0]; // -> 'a'
  626. * XRegExp('a+?', 'U').exec('aaa')[0]; // -> 'aaa'
  627. */
  628. XRegExp.addToken = function(regex, handler, options) {
  629. options = options || {};
  630. var optionalFlags = options.optionalFlags, i;
  631. if (options.flag) {
  632. registerFlag(options.flag);
  633. }
  634. if (optionalFlags) {
  635. optionalFlags = nativ.split.call(optionalFlags, '');
  636. for (i = 0; i < optionalFlags.length; ++i) {
  637. registerFlag(optionalFlags[i]);
  638. }
  639. }
  640. // Add to the private list of syntax tokens
  641. tokens.push({
  642. regex: copyRegex(regex, {
  643. addG: true,
  644. addY: hasNativeY,
  645. isInternalOnly: true
  646. }),
  647. handler: handler,
  648. scope: options.scope || defaultScope,
  649. flag: options.flag,
  650. reparse: options.reparse,
  651. leadChar: options.leadChar
  652. });
  653. // Reset the pattern cache used by the `XRegExp` constructor, since the same pattern and
  654. // flags might now produce different results
  655. XRegExp.cache.flush('patterns');
  656. };
  657. /**
  658. * Caches and returns the result of calling `XRegExp(pattern, flags)`. On any subsequent call with
  659. * the same pattern and flag combination, the cached copy of the regex is returned.
  660. *
  661. * @memberOf XRegExp
  662. * @param {String} pattern Regex pattern string.
  663. * @param {String} [flags] Any combination of XRegExp flags.
  664. * @returns {RegExp} Cached XRegExp object.
  665. * @example
  666. *
  667. * while (match = XRegExp.cache('.', 'gs').exec(str)) {
  668. * // The regex is compiled once only
  669. * }
  670. */
  671. XRegExp.cache = function(pattern, flags) {
  672. if (!regexCache[pattern]) {
  673. regexCache[pattern] = {};
  674. }
  675. return regexCache[pattern][flags] || (
  676. regexCache[pattern][flags] = XRegExp(pattern, flags)
  677. );
  678. };
  679. // Intentionally undocumented
  680. XRegExp.cache.flush = function(cacheName) {
  681. if (cacheName === 'patterns') {
  682. // Flush the pattern cache used by the `XRegExp` constructor
  683. patternCache = {};
  684. } else {
  685. // Flush the regex cache populated by `XRegExp.cache`
  686. regexCache = {};
  687. }
  688. };
  689. /**
  690. * Escapes any regular expression metacharacters, for use when matching literal strings. The result
  691. * can safely be used at any point within a regex that uses any flags.
  692. *
  693. * @memberOf XRegExp
  694. * @param {String} str String to escape.
  695. * @returns {String} String with regex metacharacters escaped.
  696. * @example
  697. *
  698. * XRegExp.escape('Escaped? <.>');
  699. * // -> 'Escaped\?\ <\.>'
  700. */
  701. XRegExp.escape = function(str) {
  702. return nativ.replace.call(toObject(str), /[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  703. };
  704. /**
  705. * Executes a regex search in a specified string. Returns a match array or `null`. If the provided
  706. * regex uses named capture, named backreference properties are included on the match array.
  707. * Optional `pos` and `sticky` arguments specify the search start position, and whether the match
  708. * must start at the specified position only. The `lastIndex` property of the provided regex is not
  709. * used, but is updated for compatibility. Also fixes browser bugs compared to the native
  710. * `RegExp.prototype.exec` and can be used reliably cross-browser.
  711. *
  712. * @memberOf XRegExp
  713. * @param {String} str String to search.
  714. * @param {RegExp} regex Regex to search with.
  715. * @param {Number} [pos=0] Zero-based index at which to start the search.
  716. * @param {Boolean|String} [sticky=false] Whether the match must start at the specified position
  717. * only. The string `'sticky'` is accepted as an alternative to `true`.
  718. * @returns {Array} Match array with named backreference properties, or `null`.
  719. * @example
  720. *
  721. * // Basic use, with named backreference
  722. * var match = XRegExp.exec('U+2620', XRegExp('U\\+(?<hex>[0-9A-F]{4})'));
  723. * match.hex; // -> '2620'
  724. *
  725. * // With pos and sticky, in a loop
  726. * var pos = 2, result = [], match;
  727. * while (match = XRegExp.exec('<1><2><3><4>5<6>', /<(\d)>/, pos, 'sticky')) {
  728. * result.push(match[1]);
  729. * pos = match.index + match[0].length;
  730. * }
  731. * // result -> ['2', '3', '4']
  732. */
  733. XRegExp.exec = function(str, regex, pos, sticky) {
  734. var cacheKey = 'g',
  735. addY = false,
  736. match,
  737. r2;
  738. addY = hasNativeY && !!(sticky || (regex.sticky && sticky !== false));
  739. if (addY) {
  740. cacheKey += 'y';
  741. }
  742. regex[REGEX_DATA] = regex[REGEX_DATA] || {};
  743. // Shares cached copies with `XRegExp.match`/`replace`
  744. r2 = regex[REGEX_DATA][cacheKey] || (
  745. regex[REGEX_DATA][cacheKey] = copyRegex(regex, {
  746. addG: true,
  747. addY: addY,
  748. removeY: sticky === false,
  749. isInternalOnly: true
  750. })
  751. );
  752. r2.lastIndex = pos = pos || 0;
  753. // Fixed `exec` required for `lastIndex` fix, named backreferences, etc.
  754. match = fixed.exec.call(r2, str);
  755. if (sticky && match && match.index !== pos) {
  756. match = null;
  757. }
  758. if (regex.global) {
  759. regex.lastIndex = match ? r2.lastIndex : 0;
  760. }
  761. return match;
  762. };
  763. /**
  764. * Executes a provided function once per regex match. Searches always start at the beginning of the
  765. * string and continue until the end, regardless of the state of the regex's `global` property and
  766. * initial `lastIndex`.
  767. *
  768. * @memberOf XRegExp
  769. * @param {String} str String to search.
  770. * @param {RegExp} regex Regex to search with.
  771. * @param {Function} callback Function to execute for each match. Invoked with four arguments:
  772. * <li>The match array, with named backreference properties.
  773. * <li>The zero-based match index.
  774. * <li>The string being traversed.
  775. * <li>The regex object being used to traverse the string.
  776. * @example
  777. *
  778. * // Extracts every other digit from a string
  779. * var evens = [];
  780. * XRegExp.forEach('1a2345', /\d/, function(match, i) {
  781. * if (i % 2) evens.push(+match[0]);
  782. * });
  783. * // evens -> [2, 4]
  784. */
  785. XRegExp.forEach = function(str, regex, callback) {
  786. var pos = 0,
  787. i = -1,
  788. match;
  789. while ((match = XRegExp.exec(str, regex, pos))) {
  790. // Because `regex` is provided to `callback`, the function could use the deprecated/
  791. // nonstandard `RegExp.prototype.compile` to mutate the regex. However, since
  792. // `XRegExp.exec` doesn't use `lastIndex` to set the search position, this can't lead
  793. // to an infinite loop, at least. Actually, because of the way `XRegExp.exec` caches
  794. // globalized versions of regexes, mutating the regex will not have any effect on the
  795. // iteration or matched strings, which is a nice side effect that brings extra safety
  796. callback(match, ++i, str, regex);
  797. pos = match.index + (match[0].length || 1);
  798. }
  799. };
  800. /**
  801. * Copies a regex object and adds flag `g`. The copy maintains extended data, is augmented with
  802. * `XRegExp.prototype` properties, and has a fresh `lastIndex` property (set to zero). Native
  803. * regexes are not recompiled using XRegExp syntax.
  804. *
  805. * @memberOf XRegExp
  806. * @param {RegExp} regex Regex to globalize.
  807. * @returns {RegExp} Copy of the provided regex with flag `g` added.
  808. * @example
  809. *
  810. * var globalCopy = XRegExp.globalize(/regex/);
  811. * globalCopy.global; // -> true
  812. */
  813. XRegExp.globalize = function(regex) {
  814. return copyRegex(regex, {addG: true});
  815. };
  816. /**
  817. * Installs optional features according to the specified options. Can be undone using
  818. * `XRegExp.uninstall`.
  819. *
  820. * @memberOf XRegExp
  821. * @param {Object|String} options Options object or string.
  822. * @example
  823. *
  824. * // With an options object
  825. * XRegExp.install({
  826. * // Enables support for astral code points in Unicode addons (implicitly sets flag A)
  827. * astral: true,
  828. *
  829. * // DEPRECATED: Overrides native regex methods with fixed/extended versions
  830. * natives: true
  831. * });
  832. *
  833. * // With an options string
  834. * XRegExp.install('astral natives');
  835. */
  836. XRegExp.install = function(options) {
  837. options = prepareOptions(options);
  838. if (!features.astral && options.astral) {
  839. setAstral(true);
  840. }
  841. if (!features.natives && options.natives) {
  842. setNatives(true);
  843. }
  844. };
  845. /**
  846. * Checks whether an individual optional feature is installed.
  847. *
  848. * @memberOf XRegExp
  849. * @param {String} feature Name of the feature to check. One of:
  850. * <li>`astral`
  851. * <li>`natives`
  852. * @returns {Boolean} Whether the feature is installed.
  853. * @example
  854. *
  855. * XRegExp.isInstalled('astral');
  856. */
  857. XRegExp.isInstalled = function(feature) {
  858. return !!(features[feature]);
  859. };
  860. /**
  861. * Returns `true` if an object is a regex; `false` if it isn't. This works correctly for regexes
  862. * created in another frame, when `instanceof` and `constructor` checks would fail.
  863. *
  864. * @memberOf XRegExp
  865. * @param {*} value Object to check.
  866. * @returns {Boolean} Whether the object is a `RegExp` object.
  867. * @example
  868. *
  869. * XRegExp.isRegExp('string'); // -> false
  870. * XRegExp.isRegExp(/regex/i); // -> true
  871. * XRegExp.isRegExp(RegExp('^', 'm')); // -> true
  872. * XRegExp.isRegExp(XRegExp('(?s).')); // -> true
  873. */
  874. XRegExp.isRegExp = function(value) {
  875. return toString.call(value) === '[object RegExp]';
  876. //return isType(value, 'RegExp');
  877. };
  878. /**
  879. * Returns the first matched string, or in global mode, an array containing all matched strings.
  880. * This is essentially a more convenient re-implementation of `String.prototype.match` that gives
  881. * the result types you actually want (string instead of `exec`-style array in match-first mode,
  882. * and an empty array instead of `null` when no matches are found in match-all mode). It also lets
  883. * you override flag g and ignore `lastIndex`, and fixes browser bugs.
  884. *
  885. * @memberOf XRegExp
  886. * @param {String} str String to search.
  887. * @param {RegExp} regex Regex to search with.
  888. * @param {String} [scope='one'] Use 'one' to return the first match as a string. Use 'all' to
  889. * return an array of all matched strings. If not explicitly specified and `regex` uses flag g,
  890. * `scope` is 'all'.
  891. * @returns {String|Array} In match-first mode: First match as a string, or `null`. In match-all
  892. * mode: Array of all matched strings, or an empty array.
  893. * @example
  894. *
  895. * // Match first
  896. * XRegExp.match('abc', /\w/); // -> 'a'
  897. * XRegExp.match('abc', /\w/g, 'one'); // -> 'a'
  898. * XRegExp.match('abc', /x/g, 'one'); // -> null
  899. *
  900. * // Match all
  901. * XRegExp.match('abc', /\w/g); // -> ['a', 'b', 'c']
  902. * XRegExp.match('abc', /\w/, 'all'); // -> ['a', 'b', 'c']
  903. * XRegExp.match('abc', /x/, 'all'); // -> []
  904. */
  905. XRegExp.match = function(str, regex, scope) {
  906. var global = (regex.global && scope !== 'one') || scope === 'all',
  907. cacheKey = ((global ? 'g' : '') + (regex.sticky ? 'y' : '')) || 'noGY',
  908. result,
  909. r2;
  910. regex[REGEX_DATA] = regex[REGEX_DATA] || {};
  911. // Shares cached copies with `XRegExp.exec`/`replace`
  912. r2 = regex[REGEX_DATA][cacheKey] || (
  913. regex[REGEX_DATA][cacheKey] = copyRegex(regex, {
  914. addG: !!global,
  915. removeG: scope === 'one',
  916. isInternalOnly: true
  917. })
  918. );
  919. result = nativ.match.call(toObject(str), r2);
  920. if (regex.global) {
  921. regex.lastIndex = (
  922. (scope === 'one' && result) ?
  923. // Can't use `r2.lastIndex` since `r2` is nonglobal in this case
  924. (result.index + result[0].length) : 0
  925. );
  926. }
  927. return global ? (result || []) : (result && result[0]);
  928. };
  929. /**
  930. * Retrieves the matches from searching a string using a chain of regexes that successively search
  931. * within previous matches. The provided `chain` array can contain regexes and or objects with
  932. * `regex` and `backref` properties. When a backreference is specified, the named or numbered
  933. * backreference is passed forward to the next regex or returned.
  934. *
  935. * @memberOf XRegExp
  936. * @param {String} str String to search.
  937. * @param {Array} chain Regexes that each search for matches within preceding results.
  938. * @returns {Array} Matches by the last regex in the chain, or an empty array.
  939. * @example
  940. *
  941. * // Basic usage; matches numbers within <b> tags
  942. * XRegExp.matchChain('1 <b>2</b> 3 <b>4 a 56</b>', [
  943. * XRegExp('(?is)<b>.*?</b>'),
  944. * /\d+/
  945. * ]);
  946. * // -> ['2', '4', '56']
  947. *
  948. * // Passing forward and returning specific backreferences
  949. * html = '<a href="http://xregexp.com/api/">XRegExp</a>\
  950. * <a href="http://www.google.com/">Google</a>';
  951. * XRegExp.matchChain(html, [
  952. * {regex: /<a href="([^"]+)">/i, backref: 1},
  953. * {regex: XRegExp('(?i)^https?://(?<domain>[^/?#]+)'), backref: 'domain'}
  954. * ]);
  955. * // -> ['xregexp.com', 'www.google.com']
  956. */
  957. XRegExp.matchChain = function(str, chain) {
  958. return (function recurseChain(values, level) {
  959. var item = chain[level].regex ? chain[level] : {regex: chain[level]},
  960. matches = [],
  961. addMatch = function(match) {
  962. if (item.backref) {
  963. /* Safari 4.0.5 (but not 5.0.5+) inappropriately uses sparse arrays to hold
  964. * the `undefined`s for backreferences to nonparticipating capturing
  965. * groups. In such cases, a `hasOwnProperty` or `in` check on its own would
  966. * inappropriately throw the exception, so also check if the backreference
  967. * is a number that is within the bounds of the array.
  968. */
  969. if (!(match.hasOwnProperty(item.backref) || +item.backref < match.length)) {
  970. throw new ReferenceError('Backreference to undefined group: ' + item.backref);
  971. }
  972. matches.push(match[item.backref] || '');
  973. } else {
  974. matches.push(match[0]);
  975. }
  976. },
  977. i;
  978. for (i = 0; i < values.length; ++i) {
  979. XRegExp.forEach(values[i], item.regex, addMatch);
  980. }
  981. return ((level === chain.length - 1) || !matches.length) ?
  982. matches :
  983. recurseChain(matches, level + 1);
  984. }([str], 0));
  985. };
  986. /**
  987. * Returns a new string with one or all matches of a pattern replaced. The pattern can be a string
  988. * or regex, and the replacement can be a string or a function to be called for each match. To
  989. * perform a global search and replace, use the optional `scope` argument or include flag g if using
  990. * a regex. Replacement strings can use `${n}` for named and numbered backreferences. Replacement
  991. * functions can use named backreferences via `arguments[0].name`. Also fixes browser bugs compared
  992. * to the native `String.prototype.replace` and can be used reliably cross-browser.
  993. *
  994. * @memberOf XRegExp
  995. * @param {String} str String to search.
  996. * @param {RegExp|String} search Search pattern to be replaced.
  997. * @param {String|Function} replacement Replacement string or a function invoked to create it.
  998. * Replacement strings can include special replacement syntax:
  999. * <li>$$ - Inserts a literal $ character.
  1000. * <li>$&, $0 - Inserts the matched substring.
  1001. * <li>$` - Inserts the string that precedes the matched substring (left context).
  1002. * <li>$' - Inserts the string that follows the matched substring (right context).
  1003. * <li>$n, $nn - Where n/nn are digits referencing an existent capturing group, inserts
  1004. * backreference n/nn.
  1005. * <li>${n} - Where n is a name or any number of digits that reference an existent capturing
  1006. * group, inserts backreference n.
  1007. * Replacement functions are invoked with three or more arguments:
  1008. * <li>The matched substring (corresponds to $& above). Named backreferences are accessible as
  1009. * properties of this first argument.
  1010. * <li>0..n arguments, one for each backreference (corresponding to $1, $2, etc. above).
  1011. * <li>The zero-based index of the match within the total search string.
  1012. * <li>The total string being searched.
  1013. * @param {String} [scope='one'] Use 'one' to replace the first match only, or 'all'. If not
  1014. * explicitly specified and using a regex with flag g, `scope` is 'all'.
  1015. * @returns {String} New string with one or all matches replaced.
  1016. * @example
  1017. *
  1018. * // Regex search, using named backreferences in replacement string
  1019. * var name = XRegExp('(?<first>\\w+) (?<last>\\w+)');
  1020. * XRegExp.replace('John Smith', name, '${last}, ${first}');
  1021. * // -> 'Smith, John'
  1022. *
  1023. * // Regex search, using named backreferences in replacement function
  1024. * XRegExp.replace('John Smith', name, function(match) {
  1025. * return match.last + ', ' + match.first;
  1026. * });
  1027. * // -> 'Smith, John'
  1028. *
  1029. * // String search, with replace-all
  1030. * XRegExp.replace('RegExp builds RegExps', 'RegExp', 'XRegExp', 'all');
  1031. * // -> 'XRegExp builds XRegExps'
  1032. */
  1033. XRegExp.replace = function(str, search, replacement, scope) {
  1034. var isRegex = XRegExp.isRegExp(search),
  1035. global = (search.global && scope !== 'one') || scope === 'all',
  1036. cacheKey = ((global ? 'g' : '') + (search.sticky ? 'y' : '')) || 'noGY',
  1037. s2 = search,
  1038. result;
  1039. if (isRegex) {
  1040. search[REGEX_DATA] = search[REGEX_DATA] || {};
  1041. // Shares cached copies with `XRegExp.exec`/`match`. Since a copy is used, `search`'s
  1042. // `lastIndex` isn't updated *during* replacement iterations
  1043. s2 = search[REGEX_DATA][cacheKey] || (
  1044. search[REGEX_DATA][cacheKey] = copyRegex(search, {
  1045. addG: !!global,
  1046. removeG: scope === 'one',
  1047. isInternalOnly: true
  1048. })
  1049. );
  1050. } else if (global) {
  1051. s2 = new RegExp(XRegExp.escape(String(search)), 'g');
  1052. }
  1053. // Fixed `replace` required for named backreferences, etc.
  1054. result = fixed.replace.call(toObject(str), s2, replacement);
  1055. if (isRegex && search.global) {
  1056. // Fixes IE, Safari bug (last tested IE 9, Safari 5.1)
  1057. search.lastIndex = 0;
  1058. }
  1059. return result;
  1060. };
  1061. /**
  1062. * Performs batch processing of string replacements. Used like `XRegExp.replace`, but accepts an
  1063. * array of replacement details. Later replacements operate on the output of earlier replacements.
  1064. * Replacement details are accepted as an array with a regex or string to search for, the
  1065. * replacement string or function, and an optional scope of 'one' or 'all'. Uses the XRegExp
  1066. * replacement text syntax, which supports named backreference properties via `${name}`.
  1067. *
  1068. * @memberOf XRegExp
  1069. * @param {String} str String to search.
  1070. * @param {Array} replacements Array of replacement detail arrays.
  1071. * @returns {String} New string with all replacements.
  1072. * @example
  1073. *
  1074. * str = XRegExp.replaceEach(str, [
  1075. * [XRegExp('(?<name>a)'), 'z${name}'],
  1076. * [/b/gi, 'y'],
  1077. * [/c/g, 'x', 'one'], // scope 'one' overrides /g
  1078. * [/d/, 'w', 'all'], // scope 'all' overrides lack of /g
  1079. * ['e', 'v', 'all'], // scope 'all' allows replace-all for strings
  1080. * [/f/g, function($0) {
  1081. * return $0.toUpperCase();
  1082. * }]
  1083. * ]);
  1084. */
  1085. XRegExp.replaceEach = function(str, replacements) {
  1086. var i, r;
  1087. for (i = 0; i < replacements.length; ++i) {
  1088. r = replacements[i];
  1089. str = XRegExp.replace(str, r[0], r[1], r[2]);
  1090. }
  1091. return str;
  1092. };
  1093. /**
  1094. * Splits a string into an array of strings using a regex or string separator. Matches of the
  1095. * separator are not included in the result array. However, if `separator` is a regex that contains
  1096. * capturing groups, backreferences are spliced into the result each time `separator` is matched.
  1097. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
  1098. * cross-browser.
  1099. *
  1100. * @memberOf XRegExp
  1101. * @param {String} str String to split.
  1102. * @param {RegExp|String} separator Regex or string to use for separating the string.
  1103. * @param {Number} [limit] Maximum number of items to include in the result array.
  1104. * @returns {Array} Array of substrings.
  1105. * @example
  1106. *
  1107. * // Basic use
  1108. * XRegExp.split('a b c', ' ');
  1109. * // -> ['a', 'b', 'c']
  1110. *
  1111. * // With limit
  1112. * XRegExp.split('a b c', ' ', 2);
  1113. * // -> ['a', 'b']
  1114. *
  1115. * // Backreferences in result array
  1116. * XRegExp.split('..word1..', /([a-z]+)(\d+)/i);
  1117. * // -> ['..', 'word', '1', '..']
  1118. */
  1119. XRegExp.split = function(str, separator, limit) {
  1120. return fixed.split.call(toObject(str), separator, limit);
  1121. };
  1122. /**
  1123. * Executes a regex search in a specified string. Returns `true` or `false`. Optional `pos` and
  1124. * `sticky` arguments specify the search start position, and whether the match must start at the
  1125. * specified position only. The `lastIndex` property of the provided regex is not used, but is
  1126. * updated for compatibility. Also fixes browser bugs compared to the native
  1127. * `RegExp.prototype.test` and can be used reliably cross-browser.
  1128. *
  1129. * @memberOf XRegExp
  1130. * @param {String} str String to search.
  1131. * @param {RegExp} regex Regex to search with.
  1132. * @param {Number} [pos=0] Zero-based index at which to start the search.
  1133. * @param {Boolean|String} [sticky=false] Whether the match must start at the specified position
  1134. * only. The string `'sticky'` is accepted as an alternative to `true`.
  1135. * @returns {Boolean} Whether the regex matched the provided value.
  1136. * @example
  1137. *
  1138. * // Basic use
  1139. * XRegExp.test('abc', /c/); // -> true
  1140. *
  1141. * // With pos and sticky
  1142. * XRegExp.test('abc', /c/, 0, 'sticky'); // -> false
  1143. * XRegExp.test('abc', /c/, 2, 'sticky'); // -> true
  1144. */
  1145. XRegExp.test = function(str, regex, pos, sticky) {
  1146. // Do this the easy way :-)
  1147. return !!XRegExp.exec(str, regex, pos, sticky);
  1148. };
  1149. /**
  1150. * Uninstalls optional features according to the specified options. All optional features start out
  1151. * uninstalled, so this is used to undo the actions of `XRegExp.install`.
  1152. *
  1153. * @memberOf XRegExp
  1154. * @param {Object|String} options Options object or string.
  1155. * @example
  1156. *
  1157. * // With an options object
  1158. * XRegExp.uninstall({
  1159. * // Disables support for astral code points in Unicode addons
  1160. * astral: true,
  1161. *
  1162. * // DEPRECATED: Restores native regex methods
  1163. * natives: true
  1164. * });
  1165. *
  1166. * // With an options string
  1167. * XRegExp.uninstall('astral natives');
  1168. */
  1169. XRegExp.uninstall = function(options) {
  1170. options = prepareOptions(options);
  1171. if (features.astral && options.astral) {
  1172. setAstral(false);
  1173. }
  1174. if (features.natives && options.natives) {
  1175. setNatives(false);
  1176. }
  1177. };
  1178. /**
  1179. * Returns an XRegExp object that is the union of the given patterns. Patterns can be provided as
  1180. * regex objects or strings. Metacharacters are escaped in patterns provided as strings.
  1181. * Backreferences in provided regex objects are automatically renumbered to work correctly within
  1182. * the larger combined pattern. Native flags used by provided regexes are ignored in favor of the
  1183. * `flags` argument.
  1184. *
  1185. * @memberOf XRegExp
  1186. * @param {Array} patterns Regexes and strings to combine.
  1187. * @param {String} [flags] Any combination of XRegExp flags.
  1188. * @returns {RegExp} Union of the provided regexes and strings.
  1189. * @example
  1190. *
  1191. * XRegExp.union(['a+b*c', /(dogs)\1/, /(cats)\1/], 'i');
  1192. * // -> /a\+b\*c|(dogs)\1|(cats)\2/i
  1193. */
  1194. XRegExp.union = function(patterns, flags) {
  1195. var parts = /(\()(?!\?)|\\([1-9]\d*)|\\[\s\S]|\[(?:[^\\\]]|\\[\s\S])*]/g,
  1196. output = [],
  1197. numCaptures = 0,
  1198. numPriorCaptures,
  1199. captureNames,
  1200. pattern,
  1201. rewrite = function(match, paren, backref) {
  1202. var name = captureNames[numCaptures - numPriorCaptures];
  1203. // Capturing group
  1204. if (paren) {
  1205. ++numCaptures;
  1206. // If the current capture has a name, preserve the name
  1207. if (name) {
  1208. return '(?<' + name + '>';
  1209. }
  1210. // Backreference
  1211. } else if (backref) {
  1212. // Rewrite the backreference
  1213. return '\\' + (+backref + numPriorCaptures);
  1214. }
  1215. return match;
  1216. },
  1217. i;
  1218. if (!(isType(patterns, 'Array') && patterns.length)) {
  1219. throw new TypeError('Must provide a nonempty array of patterns to merge');
  1220. }
  1221. for (i = 0; i < patterns.length; ++i) {
  1222. pattern = patterns[i];
  1223. if (XRegExp.isRegExp(pattern)) {
  1224. numPriorCaptures = numCaptures;
  1225. captureNames = (pattern[REGEX_DATA] && pattern[REGEX_DATA].captureNames) || [];
  1226. // Rewrite backreferences. Passing to XRegExp dies on octals and ensures patterns
  1227. // are independently valid; helps keep this simple. Named captures are put back
  1228. output.push(nativ.replace.call(XRegExp(pattern.source).source, parts, rewrite));
  1229. } else {
  1230. output.push(XRegExp.escape(pattern));
  1231. }
  1232. }
  1233. return XRegExp(output.join('|'), flags);
  1234. };
  1235. /* ==============================
  1236. * Fixed/extended native methods
  1237. * ============================== */
  1238. /**
  1239. * Adds named capture support (with backreferences returned as `result.name`), and fixes browser
  1240. * bugs in the native `RegExp.prototype.exec`. Calling `XRegExp.install('natives')` uses this to
  1241. * override the native method. Use via `XRegExp.exec` without overriding natives.
  1242. *
  1243. * @private
  1244. * @param {String} str String to search.
  1245. * @returns {Array} Match array with named backreference properties, or `null`.
  1246. */
  1247. fixed.exec = function(str) {
  1248. var origLastIndex = this.lastIndex,
  1249. match = nativ.exec.apply(this, arguments),
  1250. name,
  1251. r2,
  1252. i;
  1253. if (match) {
  1254. // Fix browsers whose `exec` methods don't return `undefined` for nonparticipating
  1255. // capturing groups. This fixes IE 5.5-8, but not IE 9's quirks mode or emulation of
  1256. // older IEs. IE 9 in standards mode follows the spec
  1257. if (!correctExecNpcg && match.length > 1 && indexOf(match, '') > -1) {
  1258. r2 = copyRegex(this, {
  1259. removeG: true,
  1260. isInternalOnly: true
  1261. });
  1262. // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed
  1263. // matching due to characters outside the match
  1264. nativ.replace.call(String(str).slice(match.index), r2, function() {
  1265. var len = arguments.length, i;
  1266. // Skip index 0 and the last 2
  1267. for (i = 1; i < len - 2; ++i) {
  1268. if (arguments[i] === undefined) {
  1269. match[i] = undefined;
  1270. }
  1271. }
  1272. });
  1273. }
  1274. // Attach named capture properties
  1275. if (this[REGEX_DATA] && this[REGEX_DATA].captureNames) {
  1276. // Skip index 0
  1277. for (i = 1; i < match.length; ++i) {
  1278. name = this[REGEX_DATA].captureNames[i - 1];
  1279. if (name) {
  1280. match[name] = match[i];
  1281. }
  1282. }
  1283. }
  1284. // Fix browsers that increment `lastIndex` after zero-length matches
  1285. if (this.global && !match[0].length && (this.lastIndex > match.index)) {
  1286. this.lastIndex = match.index;
  1287. }
  1288. }
  1289. if (!this.global) {
  1290. // Fixes IE, Opera bug (last tested IE 9, Opera 11.6)
  1291. this.lastIndex = origLastIndex;
  1292. }
  1293. return match;
  1294. };
  1295. /**
  1296. * Fixes browser bugs in the native `RegExp.prototype.test`. Calling `XRegExp.install('natives')`
  1297. * uses this to override the native method.
  1298. *
  1299. * @private
  1300. * @param {String} str String to search.
  1301. * @returns {Boolean} Whether the regex matched the provided value.
  1302. */
  1303. fixed.test = function(str) {
  1304. // Do this the easy way :-)
  1305. return !!fixed.exec.call(this, str);
  1306. };
  1307. /**
  1308. * Adds named capture support (with backreferences returned as `result.name`), and fixes browser
  1309. * bugs in the native `String.prototype.match`. Calling `XRegExp.install('natives')` uses this to
  1310. * override the native method.
  1311. *
  1312. * @private
  1313. * @param {RegExp|*} regex Regex to search with. If not a regex object, it is passed to `RegExp`.
  1314. * @returns {Array} If `regex` uses flag g, an array of match strings or `null`. Without flag g,
  1315. * the result of calling `regex.exec(this)`.
  1316. */
  1317. fixed.match = function(regex) {
  1318. var result;
  1319. if (!XRegExp.isRegExp(regex)) {
  1320. // Use the native `RegExp` rather than `XRegExp`
  1321. regex = new RegExp(regex);
  1322. } else if (regex.global) {
  1323. result = nativ.match.apply(this, arguments);
  1324. // Fixes IE bug
  1325. regex.lastIndex = 0;
  1326. return result;
  1327. }
  1328. return fixed.exec.call(regex, toObject(this));
  1329. };
  1330. /**
  1331. * Adds support for `${n}` tokens for named and numbered backreferences in replacement text, and
  1332. * provides named backreferences to replacement functions as `arguments[0].name`. Also fixes browser
  1333. * bugs in replacement text syntax when performing a replacement using a nonregex search value, and
  1334. * the value of a replacement regex's `lastIndex` property during replacement iterations and upon
  1335. * completion. Calling `XRegExp.install('natives')` uses this to override the native method. Note
  1336. * that this doesn't support SpiderMonkey's proprietary third (`flags`) argument. Use via
  1337. * `XRegExp.replace` without overriding natives.
  1338. *
  1339. * @private
  1340. * @param {RegExp|String} search Search pattern to be replaced.
  1341. * @param {String|Function} replacement Replacement string or a function invoked to create it.
  1342. * @returns {String} New string with one or all matches replaced.
  1343. */
  1344. fixed.replace = function(search, replacement) {
  1345. var isRegex = XRegExp.isRegExp(search),
  1346. origLastIndex,
  1347. captureNames,
  1348. result;
  1349. if (isRegex) {
  1350. if (search[REGEX_DATA]) {
  1351. captureNames = search[REGEX_DATA].captureNames;
  1352. }
  1353. // Only needed if `search` is nonglobal
  1354. origLastIndex = search.lastIndex;
  1355. } else {
  1356. search += ''; // Type-convert
  1357. }
  1358. // Don't use `typeof`; some older browsers return 'function' for regex objects
  1359. if (isType(replacement, 'Function')) {
  1360. // Stringifying `this` fixes a bug in IE < 9 where the last argument in replacement
  1361. // functions isn't type-converted to a string
  1362. result = nativ.replace.call(String(this), search, function() {
  1363. var args = arguments, i;
  1364. if (captureNames) {
  1365. // Change the `arguments[0]` string primitive to a `String` object that can
  1366. // store properties. This really does need to use `String` as a constructor
  1367. args[0] = new String(args[0]);
  1368. // Store named backreferences on the first argument
  1369. for (i = 0; i < captureNames.length; ++i) {
  1370. if (captureNames[i]) {
  1371. args[0][captureNames[i]] = args[i + 1];
  1372. }
  1373. }
  1374. }
  1375. // Update `lastIndex` before calling `replacement`. Fixes IE, Chrome, Firefox,
  1376. // Safari bug (last tested IE 9, Chrome 17, Firefox 11, Safari 5.1)
  1377. if (isRegex && search.global) {
  1378. search.lastIndex = args[args.length - 2] + args[0].length;
  1379. }
  1380. // ES6 specs the context for replacement functions as `undefined`
  1381. return replacement.apply(undefined, args);
  1382. });
  1383. } else {
  1384. // Ensure that the last value of `args` will be a string when given nonstring `this`,
  1385. // while still throwing on null or undefined context
  1386. result = nativ.replace.call(this == null ? this : String(this), search, function() {
  1387. // Keep this function's `arguments` available through closure
  1388. var args = arguments;
  1389. return nativ.replace.call(String(replacement), replacementToken, function($0, $1, $2) {
  1390. var n;
  1391. // Named or numbered backreference with curly braces
  1392. if ($1) {
  1393. // XRegExp behavior for `${n}`:
  1394. // 1. Backreference to numbered capture, if `n` is an integer. Use `0` for
  1395. // for the entire match. Any number of leading zeros may be used.
  1396. // 2. Backreference to named capture `n`, if it exists and is not an
  1397. // integer overridden by numbered capture. In practice, this does not
  1398. // overlap with numbered capture since XRegExp does not allow named
  1399. // capture to use a bare integer as the name.
  1400. // 3. If the name or number does not refer to an existing capturing group,
  1401. // it's an error.
  1402. n = +$1; // Type-convert; drop leading zeros
  1403. if (n <= args.length - 3) {
  1404. return args[n] || '';
  1405. }
  1406. // Groups with the same name is an error, else would need `lastIndexOf`
  1407. n = captureNames ? indexOf(captureNames, $1) : -1;
  1408. if (n < 0) {
  1409. throw new SyntaxError('Backreference to undefined group ' + $0);
  1410. }
  1411. return args[n + 1] || '';
  1412. }
  1413. // Else, special variable or numbered backreference without curly braces
  1414. if ($2 === '$') { // $$
  1415. return '$';
  1416. }
  1417. if ($2 === '&' || +$2 === 0) { // $&, $0 (not followed by 1-9), $00
  1418. return args[0];
  1419. }
  1420. if ($2 === '`') { // $` (left context)
  1421. return args[args.length - 1].slice(0, args[args.length - 2]);
  1422. }
  1423. if ($2 === "'") { // $' (right context)
  1424. return args[args.length - 1].slice(args[args.length - 2] + args[0].length);
  1425. }
  1426. // Else, numbered backreference without curly braces
  1427. $2 = +$2; // Type-convert; drop leading zero
  1428. // XRegExp behavior for `$n` and `$nn`:
  1429. // - Backrefs end after 1 or 2 digits. Use `${..}` for more digits.
  1430. // - `$1` is an error if no capturing groups.
  1431. // - `$10` is an error if less than 10 capturing groups. Use `${1}0` instead.
  1432. // - `$01` is `$1` if at least one capturing group, else it's an error.
  1433. // - `$0` (not followed by 1-9) and `$00` are the entire match.
  1434. // Native behavior, for comparison:
  1435. // - Backrefs end after 1 or 2 digits. Cannot reference capturing group 100+.
  1436. // - `$1` is a literal `$1` if no capturing groups.
  1437. // - `$10` is `$1` followed by a literal `0` if less than 10 capturing groups.
  1438. // - `$01` is `$1` if at least one capturing group, else it's a literal `$01`.
  1439. // - `$0` is a literal `$0`.
  1440. if (!isNaN($2)) {
  1441. if ($2 > args.length - 3) {
  1442. throw new SyntaxError('Backreference to undefined group ' + $0);
  1443. }
  1444. return args[$2] || '';
  1445. }
  1446. // `$` followed by an unsupported char is an error, unlike native JS
  1447. throw new SyntaxError('Invalid token ' + $0);
  1448. });
  1449. });
  1450. }
  1451. if (isRegex) {
  1452. if (search.global) {
  1453. // Fixes IE, Safari bug (last tested IE 9, Safari 5.1)
  1454. search.lastIndex = 0;
  1455. } else {
  1456. // Fixes IE, Opera bug (last tested IE 9, Opera 11.6)
  1457. search.lastIndex = origLastIndex;
  1458. }
  1459. }
  1460. return result;
  1461. };
  1462. /**
  1463. * Fixes browser bugs in the native `String.prototype.split`. Calling `XRegExp.install('natives')`
  1464. * uses this to override the native method. Use via `XRegExp.split` without overriding natives.
  1465. *
  1466. * @private
  1467. * @param {RegExp|String} separator Regex or string to use for separating the string.
  1468. * @param {Number} [limit] Maximum number of items to include in the result array.
  1469. * @returns {Array} Array of substrings.
  1470. */
  1471. fixed.split = function(separator, limit) {
  1472. if (!XRegExp.isRegExp(separator)) {
  1473. // Browsers handle nonregex split correctly, so use the faster native method
  1474. return nativ.split.apply(this, arguments);
  1475. }
  1476. var str = String(this),
  1477. output = [],
  1478. origLastIndex = separator.lastIndex,
  1479. lastLastIndex = 0,
  1480. lastLength;
  1481. // Values for `limit`, per the spec:
  1482. // If undefined: pow(2,32) - 1
  1483. // If 0, Infinity, or NaN: 0
  1484. // If positive number: limit = floor(limit); if (limit >= pow(2,32)) limit -= pow(2,32);
  1485. // If negative number: pow(2,32) - floor(abs(limit))
  1486. // If other: Type-convert, then use the above rules
  1487. // This line fails in very strange ways for some values of `limit` in Opera 10.5-10.63,
  1488. // unless Opera Dragonfly is open (go figure). It works in at least Opera 9.5-10.1 and 11+
  1489. limit = (limit === undefined ? -1 : limit) >>> 0;
  1490. XRegExp.forEach(str, separator, function(match) {
  1491. // This condition is not the same as `if (match[0].length)`
  1492. if ((match.index + match[0].length) > lastLastIndex) {
  1493. output.push(str.slice(lastLastIndex, match.index));
  1494. if (match.length > 1 && match.index < str.length) {
  1495. Array.prototype.push.apply(output, match.slice(1));
  1496. }
  1497. lastLength = match[0].length;
  1498. lastLastIndex = match.index + lastLength;
  1499. }
  1500. });
  1501. if (lastLastIndex === str.length) {
  1502. if (!nativ.test.call(separator, '') || lastLength) {
  1503. output.push('');
  1504. }
  1505. } else {
  1506. output.push(str.slice(lastLastIndex));
  1507. }
  1508. separator.lastIndex = origLastIndex;
  1509. return output.length > limit ? output.slice(0, limit) : output;
  1510. };
  1511. /* ==============================
  1512. * Built-in syntax/flag tokens
  1513. * ============================== */
  1514. /*
  1515. * Letter escapes that natively match literal characters: `\a`, `\A`, etc. These should be
  1516. * SyntaxErrors but are allowed in web reality. XRegExp makes them errors for cross-browser
  1517. * consistency and to reserve their syntax, but lets them be superseded by addons.
  1518. */
  1519. XRegExp.addToken(
  1520. /\\([ABCE-RTUVXYZaeg-mopqyz]|c(?![A-Za-z])|u(?![\dA-Fa-f]{4}|{[\dA-Fa-f]+})|x(?![\dA-Fa-f]{2}))/,
  1521. function(match, scope) {
  1522. // \B is allowed in default scope only
  1523. if (match[1] === 'B' && scope === defaultScope) {
  1524. return match[0];
  1525. }
  1526. throw new SyntaxError('Invalid escape ' + match[0]);
  1527. },
  1528. {
  1529. scope: 'all',
  1530. leadChar: '\\'
  1531. }
  1532. );
  1533. /*
  1534. * Unicode code point escape with curly braces: `\u{N..}`. `N..` is any one or more digit
  1535. * hexadecimal number from 0-10FFFF, and can include leading zeros. Requires the native ES6 `u` flag
  1536. * to support code points greater than U+FFFF. Avoids converting code points above U+FFFF to
  1537. * surrogate pairs (which could be done without flag `u`), since that could lead to broken behavior
  1538. * if you follow a `\u{N..}` token that references a code point above U+FFFF with a quantifier, or
  1539. * if you use the same in a character class.
  1540. */
  1541. XRegExp.addToken(
  1542. /\\u{([\dA-Fa-f]+)}/,
  1543. function(match, scope, flags) {
  1544. var code = dec(match[1]);
  1545. if (code > 0x10FFFF) {
  1546. throw new SyntaxError('Invalid Unicode code point ' + match[0]);
  1547. }
  1548. if (code <= 0xFFFF) {
  1549. // Converting to \uNNNN avoids needing to escape the literal character and keep it
  1550. // separate from preceding tokens
  1551. return '\\u' + pad4(hex(code));
  1552. }
  1553. // If `code` is between 0xFFFF and 0x10FFFF, require and defer to native handling
  1554. if (hasNativeU && flags.indexOf('u') > -1) {
  1555. return match[0];
  1556. }
  1557. throw new SyntaxError('Cannot use Unicode code point above \\u{FFFF} without flag u');
  1558. },
  1559. {
  1560. scope: 'all',
  1561. leadChar: '\\'
  1562. }
  1563. );
  1564. /*
  1565. * Empty character class: `[]` or `[^]`. This fixes a critical cross-browser syntax inconsistency.
  1566. * Unless this is standardized (per the ES spec), regex syntax can't be accurately parsed because
  1567. * character class endings can't be determined.
  1568. */
  1569. XRegExp.addToken(
  1570. /\[(\^?)]/,
  1571. function(match) {
  1572. // For cross-browser compatibility with ES3, convert [] to \b\B and [^] to [\s\S].
  1573. // (?!) should work like \b\B, but is unreliable in some versions of Firefox
  1574. return match[1] ? '[\\s\\S]' : '\\b\\B';
  1575. },
  1576. {leadChar: '['}
  1577. );
  1578. /*
  1579. * Comment pattern: `(?# )`. Inline comments are an alternative to the line comments allowed in
  1580. * free-spacing mode (flag x).
  1581. */
  1582. XRegExp.addToken(
  1583. /\(\?#[^)]*\)/,
  1584. function(match, scope, flags) {
  1585. // Keep tokens separated unless the following token is a quantifier
  1586. return isQuantifierNext(match.input, match.index + match[0].length, flags) ?
  1587. '' : '(?:)';
  1588. },
  1589. {leadChar: '('}
  1590. );
  1591. /*
  1592. * Whitespace and line comments, in free-spacing mode (aka extended mode, flag x) only.
  1593. */
  1594. XRegExp.addToken(
  1595. /\s+|#.*/,
  1596. function(match, scope, flags) {
  1597. // Keep tokens separated unless the following token is a quantifier
  1598. return isQuantifierNext(match.input, match.index + match[0].length, flags) ?
  1599. '' : '(?:)';
  1600. },
  1601. {flag: 'x'}
  1602. );
  1603. /*
  1604. * Dot, in dotall mode (aka singleline mode, flag s) only.
  1605. */
  1606. XRegExp.addToken(
  1607. /\./,
  1608. function() {
  1609. return '[\\s\\S]';
  1610. },
  1611. {
  1612. flag: 's',
  1613. leadChar: '.'
  1614. }
  1615. );
  1616. /*
  1617. * Named backreference: `\k<name>`. Backreference names can use the characters A-Z, a-z, 0-9, _,
  1618. * and $ only. Also allows numbered backreferences as `\k<n>`.
  1619. */
  1620. XRegExp.addToken(
  1621. /\\k<([\w$]+)>/,
  1622. function(match) {
  1623. // Groups with the same name is an error, else would need `lastIndexOf`
  1624. var index = isNaN(match[1]) ? (indexOf(this.captureNames, match[1]) + 1) : +match[1],
  1625. endIndex = match.index + match[0].length;
  1626. if (!index || index > this.captureNames.length) {
  1627. throw new SyntaxError('Backreference to undefined group ' + match[0]);
  1628. }
  1629. // Keep backreferences separate from subsequent literal numbers
  1630. return '\\' + index + (
  1631. endIndex === match.input.length || isNaN(match.input.charAt(endIndex)) ?
  1632. '' : '(?:)'
  1633. );
  1634. },
  1635. {leadChar: '\\'}
  1636. );
  1637. /*
  1638. * Numbered backreference or octal, plus any following digits: `\0`, `\11`, etc. Octals except `\0`
  1639. * not followed by 0-9 and backreferences to unopened capture groups throw an error. Other matches
  1640. * are returned unaltered. IE < 9 doesn't support backreferences above `\99` in regex syntax.
  1641. */
  1642. XRegExp.addToken(
  1643. /\\(\d+)/,
  1644. function(match, scope) {
  1645. if (
  1646. !(
  1647. scope === defaultScope &&
  1648. /^[1-9]/.test(match[1]) &&
  1649. +match[1] <= this.captureNames.length
  1650. ) &&
  1651. match[1] !== '0'
  1652. ) {
  1653. throw new SyntaxError('Cannot use octal escape or backreference to undefined group ' +
  1654. match[0]);
  1655. }
  1656. return match[0];
  1657. },
  1658. {
  1659. scope: 'all',
  1660. leadChar: '\\'
  1661. }
  1662. );
  1663. /*
  1664. * Named capturing group; match the opening delimiter only: `(?<name>`. Capture names can use the
  1665. * characters A-Z, a-z, 0-9, _, and $ only. Names can't be integers. Supports Python-style
  1666. * `(?P<name>` as an alternate syntax to avoid issues in some older versions of Opera which natively
  1667. * supported the Python-style syntax. Otherwise, XRegExp might treat numbered backreferences to
  1668. * Python-style named capture as octals.
  1669. */
  1670. XRegExp.addToken(
  1671. /\(\?P?<([\w$]+)>/,
  1672. function(match) {
  1673. // Disallow bare integers as names because named backreferences are added to match
  1674. // arrays and therefore numeric properties may lead to incorrect lookups
  1675. if (!isNaN(match[1])) {
  1676. throw new SyntaxError('Cannot use integer as capture name ' + match[0]);
  1677. }
  1678. if (match[1] === 'length' || match[1] === '__proto__') {
  1679. throw new SyntaxError('Cannot use reserved word as capture name ' + match[0]);
  1680. }
  1681. if (indexOf(this.captureNames, match[1]) > -1) {
  1682. throw new SyntaxError('Cannot use same name for multiple groups ' + match[0]);
  1683. }
  1684. this.captureNames.push(match[1]);
  1685. this.hasNamedCapture = true;
  1686. return '(';
  1687. },
  1688. {leadChar: '('}
  1689. );
  1690. /*
  1691. * Capturing group; match the opening parenthesis only. Required for support of named capturing
  1692. * groups. Also adds explicit capture mode (flag n).
  1693. */
  1694. XRegExp.addToken(
  1695. /\((?!\?)/,
  1696. function(match, scope, flags) {
  1697. if (flags.indexOf('n') > -1) {
  1698. return '(?:';
  1699. }
  1700. this.captureNames.push(null);
  1701. return '(';
  1702. },
  1703. {
  1704. optionalFlags: 'n',
  1705. leadChar: '('
  1706. }
  1707. );
  1708. /* ==============================
  1709. * Expose XRegExp
  1710. * ============================== */
  1711. module.exports = XRegExp;