forked from slevithan/xregexp
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
xregexp-all.js
4881 lines (4577 loc) · 235 KB
/
xregexp-all.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.XRegExp = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/*!
* XRegExp.build 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2012-present MIT License
*/
exports.default = function (XRegExp) {
var REGEX_DATA = 'xregexp';
var subParts = /(\()(?!\?)|\\([1-9]\d*)|\\[\s\S]|\[(?:[^\\\]]|\\[\s\S])*\]/g;
var parts = XRegExp.union([/\({{([\w$]+)}}\)|{{([\w$]+)}}/, subParts], 'g', {
conjunction: 'or'
});
/**
* Strips a leading `^` and trailing unescaped `$`, if both are present.
*
* @private
* @param {String} pattern Pattern to process.
* @returns {String} Pattern with edge anchors removed.
*/
function deanchor(pattern) {
// Allow any number of empty noncapturing groups before/after anchors, because regexes
// built/generated by XRegExp sometimes include them
var leadingAnchor = /^(?:\(\?:\))*\^/;
var trailingAnchor = /\$(?:\(\?:\))*$/;
if (leadingAnchor.test(pattern) && trailingAnchor.test(pattern) &&
// Ensure that the trailing `$` isn't escaped
trailingAnchor.test(pattern.replace(/\\[\s\S]/g, ''))) {
return pattern.replace(leadingAnchor, '').replace(trailingAnchor, '');
}
return pattern;
}
/**
* Converts the provided value to an XRegExp. Native RegExp flags are not preserved.
*
* @private
* @param {String|RegExp} value Value to convert.
* @param {Boolean} [addFlagX] Whether to apply the `x` flag in cases when `value` is not
* already a regex generated by XRegExp
* @returns {RegExp} XRegExp object with XRegExp syntax applied.
*/
function asXRegExp(value, addFlagX) {
var flags = addFlagX ? 'x' : '';
return XRegExp.isRegExp(value) ? value[REGEX_DATA] && value[REGEX_DATA].captureNames ?
// Don't recompile, to preserve capture names
value :
// Recompile as XRegExp
XRegExp(value.source, flags) :
// Compile string as XRegExp
XRegExp(value, flags);
}
function interpolate(substitution) {
return substitution instanceof RegExp ? substitution : XRegExp.escape(substitution);
}
function reduceToSubpatternsObject(subpatterns, interpolated, subpatternIndex) {
subpatterns['subpattern' + subpatternIndex] = interpolated;
return subpatterns;
}
function embedSubpatternAfter(raw, subpatternIndex, rawLiterals) {
var hasSubpattern = subpatternIndex < rawLiterals.length - 1;
return raw + (hasSubpattern ? '{{subpattern' + subpatternIndex + '}}' : '');
}
/**
* Provides tagged template literals that create regexes with XRegExp syntax and flags. The
* provided pattern is handled as a raw string, so backslashes don't need to be escaped.
*
* Interpolation of strings and regexes shares the features of `XRegExp.build`. Interpolated
* patterns are treated as atomic units when quantified, interpolated strings have their special
* characters escaped, a leading `^` and trailing unescaped `$` are stripped from interpolated
* regexes if both are present, and any backreferences within an interpolated regex are
* rewritten to work within the overall pattern.
*
* @memberOf XRegExp
* @param {String} [flags] Any combination of XRegExp flags.
* @returns {Function} Handler for template literals that construct regexes with XRegExp syntax.
* @example
*
* const h12 = /1[0-2]|0?[1-9]/;
* const h24 = /2[0-3]|[01][0-9]/;
* const hours = XRegExp.tag('x')`${h12} : | ${h24}`;
* const minutes = /^[0-5][0-9]$/;
* // Note that explicitly naming the 'minutes' group is required for named backreferences
* const time = XRegExp.tag('x')`^ ${hours} (?<minutes>${minutes}) $`;
* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
*/
XRegExp.tag = function (flags) {
return function (literals) {
for (var _len = arguments.length, substitutions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
substitutions[_key - 1] = arguments[_key];
}
var subpatterns = substitutions.map(interpolate).reduce(reduceToSubpatternsObject, {});
var pattern = literals.raw.map(embedSubpatternAfter).join('');
return XRegExp.build(pattern, subpatterns, flags);
};
};
/**
* Builds regexes using named subpatterns, for readability and pattern reuse. Backreferences in
* the outer pattern and provided subpatterns are automatically renumbered to work correctly.
* Native flags used by provided subpatterns are ignored in favor of the `flags` argument.
*
* @memberOf XRegExp
* @param {String} pattern XRegExp pattern using `{{name}}` for embedded subpatterns. Allows
* `({{name}})` as shorthand for `(?<name>{{name}})`. Patterns cannot be embedded within
* character classes.
* @param {Object} subs Lookup object for named subpatterns. Values can be strings or regexes. A
* leading `^` and trailing unescaped `$` are stripped from subpatterns, if both are present.
* @param {String} [flags] Any combination of XRegExp flags.
* @returns {RegExp} Regex with interpolated subpatterns.
* @example
*
* const time = XRegExp.build('(?x)^ {{hours}} ({{minutes}}) $', {
* hours: XRegExp.build('{{h12}} : | {{h24}}', {
* h12: /1[0-2]|0?[1-9]/,
* h24: /2[0-3]|[01][0-9]/
* }, 'x'),
* minutes: /^[0-5][0-9]$/
* });
* time.test('10:59'); // -> true
* XRegExp.exec('10:59', time).minutes; // -> '59'
*/
XRegExp.build = function (pattern, subs, flags) {
flags = flags || '';
// Used with `asXRegExp` calls for `pattern` and subpatterns in `subs`, to work around how
// some browsers convert `RegExp('\n')` to a regex that contains the literal characters `\`
// and `n`. See more details at <https://github.com/slevithan/xregexp/pull/163>.
var addFlagX = flags.indexOf('x') !== -1;
var inlineFlags = /^\(\?([\w$]+)\)/.exec(pattern);
// Add flags within a leading mode modifier to the overall pattern's flags
if (inlineFlags) {
flags = XRegExp._clipDuplicates(flags + inlineFlags[1]);
}
var data = {};
for (var p in subs) {
if (subs.hasOwnProperty(p)) {
// Passing to XRegExp enables extended syntax and ensures independent validity,
// lest an unescaped `(`, `)`, `[`, or trailing `\` breaks the `(?:)` wrapper. For
// subpatterns provided as native regexes, it dies on octals and adds the property
// used to hold extended regex instance data, for simplicity.
var sub = asXRegExp(subs[p], addFlagX);
data[p] = {
// Deanchoring allows embedding independently useful anchored regexes. If you
// really need to keep your anchors, double them (i.e., `^^...$$`).
pattern: deanchor(sub.source),
names: sub[REGEX_DATA].captureNames || []
};
}
}
// Passing to XRegExp dies on octals and ensures the outer pattern is independently valid;
// helps keep this simple. Named captures will be put back.
var patternAsRegex = asXRegExp(pattern, addFlagX);
// 'Caps' is short for 'captures'
var numCaps = 0;
var numPriorCaps = void 0;
var numOuterCaps = 0;
var outerCapsMap = [0];
var outerCapNames = patternAsRegex[REGEX_DATA].captureNames || [];
var output = patternAsRegex.source.replace(parts, function ($0, $1, $2, $3, $4) {
var subName = $1 || $2;
var capName = void 0;
var intro = void 0;
var localCapIndex = void 0;
// Named subpattern
if (subName) {
if (!data.hasOwnProperty(subName)) {
throw new ReferenceError('Undefined property ' + $0);
}
// Named subpattern was wrapped in a capturing group
if ($1) {
capName = outerCapNames[numOuterCaps];
outerCapsMap[++numOuterCaps] = ++numCaps;
// If it's a named group, preserve the name. Otherwise, use the subpattern name
// as the capture name
intro = '(?<' + (capName || subName) + '>';
} else {
intro = '(?:';
}
numPriorCaps = numCaps;
var rewrittenSubpattern = data[subName].pattern.replace(subParts, function (match, paren, backref) {
// Capturing group
if (paren) {
capName = data[subName].names[numCaps - numPriorCaps];
++numCaps;
// If the current capture has a name, preserve the name
if (capName) {
return '(?<' + capName + '>';
}
// Backreference
} else if (backref) {
localCapIndex = +backref - 1;
// Rewrite the backreference
return data[subName].names[localCapIndex] ?
// Need to preserve the backreference name in case using flag `n`
'\\k<' + data[subName].names[localCapIndex] + '>' : '\\' + (+backref + numPriorCaps);
}
return match;
});
return '' + intro + rewrittenSubpattern + ')';
}
// Capturing group
if ($3) {
capName = outerCapNames[numOuterCaps];
outerCapsMap[++numOuterCaps] = ++numCaps;
// If the current capture has a name, preserve the name
if (capName) {
return '(?<' + capName + '>';
}
// Backreference
} else if ($4) {
localCapIndex = +$4 - 1;
// Rewrite the backreference
return outerCapNames[localCapIndex] ?
// Need to preserve the backreference name in case using flag `n`
'\\k<' + outerCapNames[localCapIndex] + '>' : '\\' + outerCapsMap[+$4];
}
return $0;
});
return XRegExp(output, flags);
};
};
module.exports = exports['default'];
},{}],2:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/*!
* XRegExp.matchRecursive 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2009-present MIT License
*/
exports.default = function (XRegExp) {
/**
* Returns a match detail object composed of the provided values.
*
* @private
*/
function row(name, value, start, end) {
return {
name: name,
value: value,
start: start,
end: end
};
}
/**
* Returns an array of match strings between outermost left and right delimiters, or an array of
* objects with detailed match parts and position data. An error is thrown if delimiters are
* unbalanced within the data.
*
* @memberOf XRegExp
* @param {String} str String to search.
* @param {String} left Left delimiter as an XRegExp pattern.
* @param {String} right Right delimiter as an XRegExp pattern.
* @param {String} [flags] Any native or XRegExp flags, used for the left and right delimiters.
* @param {Object} [options] Lets you specify `valueNames` and `escapeChar` options.
* @returns {Array} Array of matches, or an empty array.
* @example
*
* // Basic usage
* let str = '(t((e))s)t()(ing)';
* XRegExp.matchRecursive(str, '\\(', '\\)', 'g');
* // -> ['t((e))s', '', 'ing']
*
* // Extended information mode with valueNames
* str = 'Here is <div> <div>an</div></div> example';
* XRegExp.matchRecursive(str, '<div\\s*>', '</div>', 'gi', {
* valueNames: ['between', 'left', 'match', 'right']
* });
* // -> [
* // {name: 'between', value: 'Here is ', start: 0, end: 8},
* // {name: 'left', value: '<div>', start: 8, end: 13},
* // {name: 'match', value: ' <div>an</div>', start: 13, end: 27},
* // {name: 'right', value: '</div>', start: 27, end: 33},
* // {name: 'between', value: ' example', start: 33, end: 41}
* // ]
*
* // Omitting unneeded parts with null valueNames, and using escapeChar
* str = '...{1}.\\{{function(x,y){return {y:x}}}';
* XRegExp.matchRecursive(str, '{', '}', 'g', {
* valueNames: ['literal', null, 'value', null],
* escapeChar: '\\'
* });
* // -> [
* // {name: 'literal', value: '...', start: 0, end: 3},
* // {name: 'value', value: '1', start: 4, end: 5},
* // {name: 'literal', value: '.\\{', start: 6, end: 9},
* // {name: 'value', value: 'function(x,y){return {y:x}}', start: 10, end: 37}
* // ]
*
* // Sticky mode via flag y
* str = '<1><<<2>>><3>4<5>';
* XRegExp.matchRecursive(str, '<', '>', 'gy');
* // -> ['1', '<<2>>', '3']
*/
XRegExp.matchRecursive = function (str, left, right, flags, options) {
flags = flags || '';
options = options || {};
var global = flags.indexOf('g') !== -1;
var sticky = flags.indexOf('y') !== -1;
// Flag `y` is controlled internally
var basicFlags = flags.replace(/y/g, '');
var _options = options,
escapeChar = _options.escapeChar;
var vN = options.valueNames;
var output = [];
var openTokens = 0;
var delimStart = 0;
var delimEnd = 0;
var lastOuterEnd = 0;
var outerStart = void 0;
var innerStart = void 0;
var leftMatch = void 0;
var rightMatch = void 0;
var esc = void 0;
left = XRegExp(left, basicFlags);
right = XRegExp(right, basicFlags);
if (escapeChar) {
if (escapeChar.length > 1) {
throw new Error('Cannot use more than one escape character');
}
escapeChar = XRegExp.escape(escapeChar);
// Example of concatenated `esc` regex:
// `escapeChar`: '%'
// `left`: '<'
// `right`: '>'
// Regex is: /(?:%[\S\s]|(?:(?!<|>)[^%])+)+/
esc = new RegExp('(?:' + escapeChar + '[\\S\\s]|(?:(?!' +
// Using `XRegExp.union` safely rewrites backreferences in `left` and `right`.
// Intentionally not passing `basicFlags` to `XRegExp.union` since any syntax
// transformation resulting from those flags was already applied to `left` and
// `right` when they were passed through the XRegExp constructor above.
XRegExp.union([left, right], '', { conjunction: 'or' }).source + ')[^' + escapeChar + '])+)+',
// Flags `gy` not needed here
flags.replace(/[^imu]+/g, ''));
}
while (true) {
// If using an escape character, advance to the delimiter's next starting position,
// skipping any escaped characters in between
if (escapeChar) {
delimEnd += (XRegExp.exec(str, esc, delimEnd, 'sticky') || [''])[0].length;
}
leftMatch = XRegExp.exec(str, left, delimEnd);
rightMatch = XRegExp.exec(str, right, delimEnd);
// Keep the leftmost match only
if (leftMatch && rightMatch) {
if (leftMatch.index <= rightMatch.index) {
rightMatch = null;
} else {
leftMatch = null;
}
}
// Paths (LM: leftMatch, RM: rightMatch, OT: openTokens):
// LM | RM | OT | Result
// 1 | 0 | 1 | loop
// 1 | 0 | 0 | loop
// 0 | 1 | 1 | loop
// 0 | 1 | 0 | throw
// 0 | 0 | 1 | throw
// 0 | 0 | 0 | break
// The paths above don't include the sticky mode special case. The loop ends after the
// first completed match if not `global`.
if (leftMatch || rightMatch) {
delimStart = (leftMatch || rightMatch).index;
delimEnd = delimStart + (leftMatch || rightMatch)[0].length;
} else if (!openTokens) {
break;
}
if (sticky && !openTokens && delimStart > lastOuterEnd) {
break;
}
if (leftMatch) {
if (!openTokens) {
outerStart = delimStart;
innerStart = delimEnd;
}
++openTokens;
} else if (rightMatch && openTokens) {
if (! --openTokens) {
if (vN) {
if (vN[0] && outerStart > lastOuterEnd) {
output.push(row(vN[0], str.slice(lastOuterEnd, outerStart), lastOuterEnd, outerStart));
}
if (vN[1]) {
output.push(row(vN[1], str.slice(outerStart, innerStart), outerStart, innerStart));
}
if (vN[2]) {
output.push(row(vN[2], str.slice(innerStart, delimStart), innerStart, delimStart));
}
if (vN[3]) {
output.push(row(vN[3], str.slice(delimStart, delimEnd), delimStart, delimEnd));
}
} else {
output.push(str.slice(innerStart, delimStart));
}
lastOuterEnd = delimEnd;
if (!global) {
break;
}
}
} else {
// For our purposes this mustn't throw, return null instead
return null;
}
// If the delimiter matched an empty string, avoid an infinite loop
if (delimStart === delimEnd) {
++delimEnd;
}
}
if (global && !sticky && vN && vN[0] && str.length > lastOuterEnd) {
output.push(row(vN[0], str.slice(lastOuterEnd), lastOuterEnd, str.length));
}
return output;
};
};
module.exports = exports['default'];
},{}],3:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/*!
* XRegExp Unicode Base 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2008-present MIT License
*/
exports.default = function (XRegExp) {
/**
* Adds base support for Unicode matching:
* - Adds syntax `\p{..}` for matching Unicode tokens. Tokens can be inverted using `\P{..}` or
* `\p{^..}`. Token names ignore case, spaces, hyphens, and underscores. You can omit the
* braces for token names that are a single letter (e.g. `\pL` or `PL`).
* - Adds flag A (astral), which enables 21-bit Unicode support.
* - Adds the `XRegExp.addUnicodeData` method used by other addons to provide character data.
*
* Unicode Base relies on externally provided Unicode character data. Official addons are
* available to provide data for Unicode categories, scripts, blocks, and properties.
*
* @requires XRegExp
*/
// ==--------------------------==
// Private stuff
// ==--------------------------==
// Storage for Unicode data
var unicode = {};
// Reuse utils
var dec = XRegExp._dec;
var hex = XRegExp._hex;
var pad4 = XRegExp._pad4;
// Generates a token lookup name: lowercase, with hyphens, spaces, and underscores removed
function normalize(name) {
return name.replace(/[- _]+/g, '').toLowerCase();
}
// Gets the decimal code of a literal code unit, \xHH, \uHHHH, or a backslash-escaped literal
function charCode(chr) {
var esc = /^\\[xu](.+)/.exec(chr);
return esc ? dec(esc[1]) : chr.charCodeAt(chr[0] === '\\' ? 1 : 0);
}
// Inverts a list of ordered BMP characters and ranges
function invertBmp(range) {
var output = '';
var lastEnd = -1;
XRegExp.forEach(range, /(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/, function (m) {
var start = charCode(m[1]);
if (start > lastEnd + 1) {
output += '\\u' + pad4(hex(lastEnd + 1));
if (start > lastEnd + 2) {
output += '-\\u' + pad4(hex(start - 1));
}
}
lastEnd = charCode(m[2] || m[1]);
});
if (lastEnd < 0xFFFF) {
output += '\\u' + pad4(hex(lastEnd + 1));
if (lastEnd < 0xFFFE) {
output += '-\\uFFFF';
}
}
return output;
}
// Generates an inverted BMP range on first use
function cacheInvertedBmp(slug) {
var prop = 'b!';
return unicode[slug][prop] || (unicode[slug][prop] = invertBmp(unicode[slug].bmp));
}
// Combines and optionally negates BMP and astral data
function buildAstral(slug, isNegated) {
var item = unicode[slug];
var combined = '';
if (item.bmp && !item.isBmpLast) {
combined = '[' + item.bmp + ']' + (item.astral ? '|' : '');
}
if (item.astral) {
combined += item.astral;
}
if (item.isBmpLast && item.bmp) {
combined += (item.astral ? '|' : '') + '[' + item.bmp + ']';
}
// Astral Unicode tokens always match a code point, never a code unit
return isNegated ? '(?:(?!' + combined + ')(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|[\0-\uFFFF]))' : '(?:' + combined + ')';
}
// Builds a complete astral pattern on first use
function cacheAstral(slug, isNegated) {
var prop = isNegated ? 'a!' : 'a=';
return unicode[slug][prop] || (unicode[slug][prop] = buildAstral(slug, isNegated));
}
// ==--------------------------==
// Core functionality
// ==--------------------------==
/*
* Add astral mode (flag A) and Unicode token syntax: `\p{..}`, `\P{..}`, `\p{^..}`, `\pC`.
*/
XRegExp.addToken(
// Use `*` instead of `+` to avoid capturing `^` as the token name in `\p{^}`
/\\([pP])(?:{(\^?)([^}]*)}|([A-Za-z]))/, function (match, scope, flags) {
var ERR_DOUBLE_NEG = 'Invalid double negation ';
var ERR_UNKNOWN_NAME = 'Unknown Unicode token ';
var ERR_UNKNOWN_REF = 'Unicode token missing data ';
var ERR_ASTRAL_ONLY = 'Astral mode required for Unicode token ';
var ERR_ASTRAL_IN_CLASS = 'Astral mode does not support Unicode tokens within character classes';
// Negated via \P{..} or \p{^..}
var isNegated = match[1] === 'P' || !!match[2];
// Switch from BMP (0-FFFF) to astral (0-10FFFF) mode via flag A
var isAstralMode = flags.indexOf('A') !== -1;
// Token lookup name. Check `[4]` first to avoid passing `undefined` via `\p{}`
var slug = normalize(match[4] || match[3]);
// Token data object
var item = unicode[slug];
if (match[1] === 'P' && match[2]) {
throw new SyntaxError(ERR_DOUBLE_NEG + match[0]);
}
if (!unicode.hasOwnProperty(slug)) {
throw new SyntaxError(ERR_UNKNOWN_NAME + match[0]);
}
// Switch to the negated form of the referenced Unicode token
if (item.inverseOf) {
slug = normalize(item.inverseOf);
if (!unicode.hasOwnProperty(slug)) {
throw new ReferenceError(ERR_UNKNOWN_REF + match[0] + ' -> ' + item.inverseOf);
}
item = unicode[slug];
isNegated = !isNegated;
}
if (!(item.bmp || isAstralMode)) {
throw new SyntaxError(ERR_ASTRAL_ONLY + match[0]);
}
if (isAstralMode) {
if (scope === 'class') {
throw new SyntaxError(ERR_ASTRAL_IN_CLASS);
}
return cacheAstral(slug, isNegated);
}
return scope === 'class' ? isNegated ? cacheInvertedBmp(slug) : item.bmp : (isNegated ? '[^' : '[') + item.bmp + ']';
}, {
scope: 'all',
optionalFlags: 'A',
leadChar: '\\'
});
/**
* Adds to the list of Unicode tokens that XRegExp regexes can match via `\p` or `\P`.
*
* @memberOf XRegExp
* @param {Array} data Objects with named character ranges. Each object may have properties
* `name`, `alias`, `isBmpLast`, `inverseOf`, `bmp`, and `astral`. All but `name` are
* optional, although one of `bmp` or `astral` is required (unless `inverseOf` is set). If
* `astral` is absent, the `bmp` data is used for BMP and astral modes. If `bmp` is absent,
* the name errors in BMP mode but works in astral mode. If both `bmp` and `astral` are
* provided, the `bmp` data only is used in BMP mode, and the combination of `bmp` and
* `astral` data is used in astral mode. `isBmpLast` is needed when a token matches orphan
* high surrogates *and* uses surrogate pairs to match astral code points. The `bmp` and
* `astral` data should be a combination of literal characters and `\xHH` or `\uHHHH` escape
* sequences, with hyphens to create ranges. Any regex metacharacters in the data should be
* escaped, apart from range-creating hyphens. The `astral` data can additionally use
* character classes and alternation, and should use surrogate pairs to represent astral code
* points. `inverseOf` can be used to avoid duplicating character data if a Unicode token is
* defined as the exact inverse of another token.
* @example
*
* // Basic use
* XRegExp.addUnicodeData([{
* name: 'XDigit',
* alias: 'Hexadecimal',
* bmp: '0-9A-Fa-f'
* }]);
* XRegExp('\\p{XDigit}:\\p{Hexadecimal}+').test('0:3D'); // -> true
*/
XRegExp.addUnicodeData = function (data) {
var ERR_NO_NAME = 'Unicode token requires name';
var ERR_NO_DATA = 'Unicode token has no character data ';
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var item = _step.value;
if (!item.name) {
throw new Error(ERR_NO_NAME);
}
if (!(item.inverseOf || item.bmp || item.astral)) {
throw new Error(ERR_NO_DATA + item.name);
}
unicode[normalize(item.name)] = item;
if (item.alias) {
unicode[normalize(item.alias)] = item;
}
}
// Reset the pattern cache used by the `XRegExp` constructor, since the same pattern and
// flags might now produce different results
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
XRegExp.cache.flush('patterns');
};
/**
* @ignore
*
* Return a reference to the internal Unicode definition structure for the given Unicode
* Property if the given name is a legal Unicode Property for use in XRegExp `\p` or `\P` regex
* constructs.
*
* @memberOf XRegExp
* @param {String} name Name by which the Unicode Property may be recognized (case-insensitive),
* e.g. `'N'` or `'Number'`. The given name is matched against all registered Unicode
* Properties and Property Aliases.
* @returns {Object} Reference to definition structure when the name matches a Unicode Property.
*
* @note
* For more info on Unicode Properties, see also http://unicode.org/reports/tr18/#Categories.
*
* @note
* This method is *not* part of the officially documented API and may change or be removed in
* the future. It is meant for userland code that wishes to reuse the (large) internal Unicode
* structures set up by XRegExp.
*/
XRegExp._getUnicodeProperty = function (name) {
var slug = normalize(name);
return unicode[slug];
};
};
module.exports = exports['default'];
},{}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _blocks = require('../../tools/output/blocks');
var _blocks2 = _interopRequireDefault(_blocks);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (XRegExp) {
/**
* Adds support for all Unicode blocks. Block names use the prefix 'In'. E.g.,
* `\p{InBasicLatin}`. Token names are case insensitive, and any spaces, hyphens, and
* underscores are ignored.
*
* Uses Unicode 10.0.0.
*
* @requires XRegExp, Unicode Base
*/
if (!XRegExp.addUnicodeData) {
throw new ReferenceError('Unicode Base must be loaded before Unicode Blocks');
}
XRegExp.addUnicodeData(_blocks2.default);
}; /*!
* XRegExp Unicode Blocks 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2010-present MIT License
* Unicode data by Mathias Bynens <mathiasbynens.be>
*/
module.exports = exports['default'];
},{"../../tools/output/blocks":10}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _categories = require('../../tools/output/categories');
var _categories2 = _interopRequireDefault(_categories);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (XRegExp) {
/**
* Adds support for Unicode's general categories. E.g., `\p{Lu}` or `\p{Uppercase Letter}`. See
* category descriptions in UAX #44 <http://unicode.org/reports/tr44/#GC_Values_Table>. Token
* names are case insensitive, and any spaces, hyphens, and underscores are ignored.
*
* Uses Unicode 10.0.0.
*
* @requires XRegExp, Unicode Base
*/
if (!XRegExp.addUnicodeData) {
throw new ReferenceError('Unicode Base must be loaded before Unicode Categories');
}
XRegExp.addUnicodeData(_categories2.default);
}; /*!
* XRegExp Unicode Categories 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2010-present MIT License
* Unicode data by Mathias Bynens <mathiasbynens.be>
*/
module.exports = exports['default'];
},{"../../tools/output/categories":11}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _properties = require('../../tools/output/properties');
var _properties2 = _interopRequireDefault(_properties);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (XRegExp) {
/**
* Adds properties to meet the UTS #18 Level 1 RL1.2 requirements for Unicode regex support. See
* <http://unicode.org/reports/tr18/#RL1.2>. Following are definitions of these properties from
* UAX #44 <http://unicode.org/reports/tr44/>:
*
* - Alphabetic
* Characters with the Alphabetic property. Generated from: Lowercase + Uppercase + Lt + Lm +
* Lo + Nl + Other_Alphabetic.
*
* - Default_Ignorable_Code_Point
* For programmatic determination of default ignorable code points. New characters that should
* be ignored in rendering (unless explicitly supported) will be assigned in these ranges,
* permitting programs to correctly handle the default rendering of such characters when not
* otherwise supported.
*
* - Lowercase
* Characters with the Lowercase property. Generated from: Ll + Other_Lowercase.
*
* - Noncharacter_Code_Point
* Code points permanently reserved for internal use.
*
* - Uppercase
* Characters with the Uppercase property. Generated from: Lu + Other_Uppercase.
*
* - White_Space
* Spaces, separator characters and other control characters which should be treated by
* programming languages as "white space" for the purpose of parsing elements.
*
* The properties ASCII, Any, and Assigned are also included but are not defined in UAX #44. UTS
* #18 RL1.2 additionally requires support for Unicode scripts and general categories. These are
* included in XRegExp's Unicode Categories and Unicode Scripts addons.
*
* Token names are case insensitive, and any spaces, hyphens, and underscores are ignored.
*
* Uses Unicode 10.0.0.
*
* @requires XRegExp, Unicode Base
*/
if (!XRegExp.addUnicodeData) {
throw new ReferenceError('Unicode Base must be loaded before Unicode Properties');
}
var unicodeData = _properties2.default;
// Add non-generated data
unicodeData.push({
name: 'Assigned',
// Since this is defined as the inverse of Unicode category Cn (Unassigned), the Unicode
// Categories addon is required to use this property
inverseOf: 'Cn'
});
XRegExp.addUnicodeData(unicodeData);
}; /*!
* XRegExp Unicode Properties 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2012-present MIT License
* Unicode data by Mathias Bynens <mathiasbynens.be>
*/
module.exports = exports['default'];
},{"../../tools/output/properties":12}],7:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _scripts = require('../../tools/output/scripts');
var _scripts2 = _interopRequireDefault(_scripts);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (XRegExp) {
/**
* Adds support for all Unicode scripts. E.g., `\p{Latin}`. Token names are case insensitive,
* and any spaces, hyphens, and underscores are ignored.
*
* Uses Unicode 10.0.0.
*
* @requires XRegExp, Unicode Base
*/
if (!XRegExp.addUnicodeData) {
throw new ReferenceError('Unicode Base must be loaded before Unicode Scripts');
}
XRegExp.addUnicodeData(_scripts2.default);
}; /*!
* XRegExp Unicode Scripts 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2010-present MIT License
* Unicode data by Mathias Bynens <mathiasbynens.be>
*/
module.exports = exports['default'];
},{"../../tools/output/scripts":13}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _xregexp = require('./xregexp');
var _xregexp2 = _interopRequireDefault(_xregexp);
var _build = require('./addons/build');
var _build2 = _interopRequireDefault(_build);
var _matchrecursive = require('./addons/matchrecursive');
var _matchrecursive2 = _interopRequireDefault(_matchrecursive);
var _unicodeBase = require('./addons/unicode-base');
var _unicodeBase2 = _interopRequireDefault(_unicodeBase);
var _unicodeBlocks = require('./addons/unicode-blocks');
var _unicodeBlocks2 = _interopRequireDefault(_unicodeBlocks);
var _unicodeCategories = require('./addons/unicode-categories');
var _unicodeCategories2 = _interopRequireDefault(_unicodeCategories);
var _unicodeProperties = require('./addons/unicode-properties');
var _unicodeProperties2 = _interopRequireDefault(_unicodeProperties);
var _unicodeScripts = require('./addons/unicode-scripts');
var _unicodeScripts2 = _interopRequireDefault(_unicodeScripts);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _build2.default)(_xregexp2.default);
(0, _matchrecursive2.default)(_xregexp2.default);
(0, _unicodeBase2.default)(_xregexp2.default);
(0, _unicodeBlocks2.default)(_xregexp2.default);
(0, _unicodeCategories2.default)(_xregexp2.default);
(0, _unicodeProperties2.default)(_xregexp2.default);
(0, _unicodeScripts2.default)(_xregexp2.default);
exports.default = _xregexp2.default;
module.exports = exports['default'];
},{"./addons/build":1,"./addons/matchrecursive":2,"./addons/unicode-base":3,"./addons/unicode-blocks":4,"./addons/unicode-categories":5,"./addons/unicode-properties":6,"./addons/unicode-scripts":7,"./xregexp":9}],9:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
/*!
* XRegExp 4.1.1
* <xregexp.com>
* Steven Levithan (c) 2007-present MIT License
*/
/**
* XRegExp provides augmented, extensible regular expressions. You get additional regex syntax and
* flags, beyond what browsers support natively. XRegExp is also a regex utility belt with tools to
* make your client-side grepping simpler and more powerful, while freeing you from related
* cross-browser inconsistencies.
*/
// ==--------------------------==
// Private stuff
// ==--------------------------==
// Property name used for extended regex instance data
var REGEX_DATA = 'xregexp';
// Optional features that can be installed and uninstalled
var features = {
astral: false,
namespacing: false
};
// Native methods to use and restore ('native' is an ES3 reserved keyword)
var nativ = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split
};
// Storage for fixed/extended native methods
var fixed = {};