-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.js
1479 lines (1307 loc) · 49.1 KB
/
regexp.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
/* vim:set fileencoding=utf-8 tabstop=2 shiftwidth=2 softtabstop=2 expandtab: */
/**
* <title>PointedEars' JSX: RegExp Library</title>
* @filename regexp.js
* @version $Id$
*
* @section Copyright & Disclaimer
*
* @author
* (C) 2005, 2009-2017 Thomas Lahn <js@PointedEars.de>
*
* @partof PointedEars' JavaScript Extensions (JSX)
*
* JSX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JSX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JSX. If not, see <http://www.gnu.org/licenses/>.
*/
if (typeof jsx != "object")
{
/**
* @namespace
*/
var jsx = {};
}
(function () {
"use strict";
var _jsx_object = jsx.object;
var _ADD_OVERWRITE = _jsx_object.ADD_OVERWRITE;
var _extend = _jsx_object.extend;
var _getClass = _jsx_object.getClass;
var _getKeys = _jsx_object.getKeys;
var _getDataObject = _jsx_object.getDataObject;
var _isString = _jsx_object.isString;
/**
* @namespace
* @property pattern : String
* The original pattern string, including pattern-match
* modifiers.
* @property _patternGroups : Array
* The part of the pattern string from the opening parenthesis
* of each pattern group to the end of the pattern, before
* character class expansion, and without pattern-match
* modifiers. The first item (index 0) holds the complete
* pattern without modifiers. Used internally; do not modify.
* <em>NOTE: For efficiency, the pattern groups are not isolated;
* further parsing on your part may very well be necessary.</em>
* @property groups : Object
* An Array-like object mapping group indexes to group names.
* Its <code>length</code> property yields the number of grouped
* subpatterns in the original pattern, including named groups.
* @property names : Object
* An object mapping group names to group indexes.
* @property flags : String
* The original flags string
* @property dotAll : boolean
* Flag specifying whether the used expression was built from
* a pattern where the dot matches newline as well (PCRE_DOTALL).
* @property extended : boolean
* Flag specifying whether the used expression was built from
* an extended pattern (PCRE_EXTENDED).
* @property unicodeMode : boolean
* Flag specifying whether the used expression was built using
* Unicode mode.
* @method exec
* A variant of the built-in {@link RegExp.prototype#exec()}
* to support named groups and Unicode mode transparently.
* @method _oldExec
* The original inherited exec() method. Used internally.
* @method _realExec
* The used exec() method. Used internally.
* @function
*/
var _RegExp2 = jsx.object.extend(
(
function () {
var
_destructure = jsx.array.destructure,
_WideString = _jsx_object.getFeature(
jsx, "string", "unicode", "WideString"),
_fromCharCode = function (codePoint) {
if (codePoint > 0xFFFF)
{
return _WideString.fromCharCode(codePoint);
}
return String.fromCharCode(codePoint);
},
propertyClasses,
ucdFields = ["codePoint",, "propertyClass"],
_beyondBMPsupport = jsx.tryThis(
function () {
new RegExp("", "u");
return true;
},
function () {
return false;
}
),
_parseUCDText = function () {
(new jsx.net.http.Request(
_RegExp2.ucdTextPath, "GET", false,
function (xhr) {
var lines = xhr.responseText.split(/\r?\n|\r/).map(
function (e) {
var entry = _destructure(e.split(";"), ucdFields);
entry.codePoint = parseInt(entry.codePoint, 16);
return entry;
});
lines.sort(function (a, b) {
if (a.propertyClass < b.propertyClass) return -1;
if (a.propertyClass > b.propertyClass) return 1;
if (a.codePoint < b.codePoint) return -1;
if (a.codePoint > b.codePoint) return 1;
return 0;
});
propertyClasses = _RegExp2.propertyClasses = {};
for (var i = 0, len = lines.length; i < len; ++i)
{
var
line = lines[i],
propertyClass = line.propertyClass,
prevClass,
codePoint = line.codePoint,
prevCodePoint;
if (isNaN(codePoint)
|| (codePoint > 0xFFFF && (!_WideString || !_beyondBMPsupport)))
{
continue;
}
if (propertyClass != prevClass)
{
if (codePoint != prevCodePoint + 1)
{
if (startRange)
{
propertyClasses[prevClass] += ("-" + _fromCharCode(prevCodePoint));
}
}
propertyClasses[propertyClass] = _fromCharCode(codePoint);
var startRange = false;
}
else
{
if (codePoint != prevCodePoint + 1)
{
if (startRange)
{
propertyClasses[prevClass] += ("-" + _fromCharCode(prevCodePoint));
startRange = false;
}
propertyClasses[propertyClass] += _fromCharCode(codePoint);
}
else
{
startRange = true;
}
}
prevClass = propertyClass,
prevCodePoint = codePoint;
}
if (startRange)
{
propertyClasses[prevClass] += ("-" + _fromCharCode(prevCodePoint));
}
}
)).send();
},
sPropertyEscapes = /\\(p)\{([^\}]+)\}/.source,
rxNegEscape = new RegExp(sPropertyEscapes.toUpperCase() + /|\\([DSW])/.source, "g"),
/**
* @param {String} charClassContent
* @param {boolean} bUnicodeMode
* @return {string}
*/
_normalizeCharClass = function (charClassContent, bUnicodeMode) {
var negEscapes = [];
if (charClassContent == "") return "[]";
if (charClassContent == "^") return "[^]";
var reduced = charClassContent.replace(
rxNegEscape,
function (m, cP, charProperty, cDSW) {
var escapeChar = cP || cDSW;
if (escapeChar == "P" || bUnicodeMode)
{
negEscapes.push("\\" + escapeChar.toLowerCase()
+ (charProperty ? "{" + charProperty + "}" : ""));
return "";
}
return m;
});
if (negEscapes.length > 0)
{
/* Do not let negated empty class from reduction match everything */
if (reduced == "^")
{
reduced = "";
}
if (reduced !== "")
{
jsx.warn(
"jsx.regexp.RegExp: Combined negative escapes in character classes"
+ " require support for non-capturing parentheses");
}
return (reduced ? "(?:[" + reduced + "]|" : "")
+ "[" + (charClassContent.charAt(0) == "^" ? "" : "^")
+ negEscapes.join("") + "]"
+ (reduced ? ")" : "");
}
return "[" + reduced + "]";
},
rxPropertyEscapes = new RegExp(sPropertyEscapes, "gi"),
sNonPropEscInRange = /([^\]\\]|\\[^p])*/.source,
sEscapes =
"\\[(\\^?(" + sNonPropEscInRange + "(" + sPropertyEscapes
+ ")+" + sNonPropEscInRange + ")+)\\]"
+ "|" + sPropertyEscapes + "",
rxEscapes = new RegExp(sEscapes, "gi"),
/*jshint -W072*/
fEscapeMapper = function (match, classRanges, p2, p3, p4, p5, p6, p7,
standalonePropSpec, standaloneClass) {
propertyClasses = _RegExp2.propertyClasses;
/* If the Unicode Character Database (UCD) is not statically loaded */
if (!propertyClasses)
{
/* load it dynamically, ignore exceptions */
var ucdScriptPath = _RegExp2.ucdScriptPath;
if (ucdScriptPath)
{
jsx.tryThis(function () { jsx.importFrom(ucdScriptPath); });
propertyClasses = _RegExp2.propertyClasses;
}
/* if this failed */
if (!propertyClasses)
{
if (!jsx.net || !jsx.net.http || typeof jsx.net.http.Request != "function")
{
jsx.throwThis("jsx.regexp.UCDLoadError",
['"' + _RegExp2.ucdScriptPath + '" (jsx.regexp.RegExp.ucdScriptPath)',
"http.js"]);
}
/* parse the text version of the UCD */
_parseUCDText();
}
}
/*
* Define property classes required for Unicode mode
* if not already defined
*/
_jsx_object.extend(propertyClasses, {
L: "\\p{Ll}\\p{Lm}\\p{Lo}\\p{Lt}\\p{Lu}",
M: "\\p{Mc}\\p{Me}\\p{Mn}",
N: "\\p{Nd}\\p{Nl}\\p{No}",
Digit: "\\p{Nd}",
Space: "\u0009\u000a\u000c\u000d\u0020\u0085\u00a0"
+ "\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005"
+ "\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f"
+ "\u205f\u3000",
Word: "\\p{L}\\p{M}\\p{N}\\p{Pc}"
});
var _rangesStack = _getDataObject({
seen: _getDataObject(),
items: [],
indexOf: function (item) {
item = this.seen[item];
return (item ? item.index : -1);
},
pop: function () {
var items = this.items;
var last = items.pop();
delete this.seen[last];
this.length = items.length;
return last;
},
push: function (item) {
var items = this.items;
this.seen[item] = _getDataObject({index: items.length});
items.push(item);
this.length = items.length;
},
/**
* @return {string}
*/
toString: function () {
return this.items.join(" --> ");
}
});
var _propertyClassReplacer = function (match, propertySpecifier, propertyClass) {
if (propertySpecifier === "P")
{
jsx.throwThis("jsx.regexp.InvalidPropertyClassError",
_rangesStack.pop()
+ " contains the negative property specifier \\P{" + propertyClass + "}");
return;
}
return _getRanges(propertyClass);
};
var _getRanges =
/**
* Retrieves class ranges by property class, and throws a specialized
* exception if this fails.
* @param {String} propertyClass
* @throws jsx.regexp#UndefinedPropertyClassError
*/
function (propertyClass) {
return jsx.tryThis(
function () {
if (_rangesStack.indexOf(propertyClass) > -1)
{
jsx.throwThis("jsx.regexp.InvalidPropertyClassError",
propertyClass + " is cyclically defined ("
+ _rangesStack + " --> " + propertyClass
+ ")");
return;
}
_rangesStack.push(propertyClass);
var escapedRange = _jsx_object.getProperty(propertyClasses, propertyClass);
/*
* Resolve property class references in property class values,
* watch for cyclic structures.
*/
var rxPropertyEscapes = new RegExp(sPropertyEscapes, "gi");
var unescapedRange = escapedRange.replace(rxPropertyEscapes, _propertyClassReplacer);
_rangesStack.pop();
return unescapedRange;
},
function (e) {
if (e.name == "jsx.object.PropertyError")
{
jsx.throwThis("jsx.regexp.UndefinedPropertyClassError",
propertyClass + (_rangesStack.length > 1 ? " in " + _rangesStack : ""));
}
else
{
jsx.rethrowThis(e);
}
});
};
/* We can handle standalone class references … */
if (standaloneClass)
{
var result = _getRanges(standaloneClass);
result = "[" + (standalonePropSpec == "P" ? "^" : "") + result + "]";
}
else
{
/* … and class references in character classes */
result = _normalizeCharClass(classRanges);
result = result.replace(
rxPropertyEscapes,
function (match, propertySpecifier, propertyClass) {
var ranges = _getRanges(propertyClass);
return ranges;
});
}
return result;
};
/*jshint +W072*/
/**
* Creates and returns an extended {@link RegExp} object.
*
* This constructor accepts pattern and flags arguments where you
* can use some features of Perl and Perl-compatible regular
* expressions (PCRE); like {@link RegExp()}, it can also be called
* as a function to do the same. The {@link RegExp} instance it
* returns is augmented with properties to support those features
* when matching it against a string.
*
* The following additional features are currently supported:
* <ul>
* <li>Flags:
* <ul>
* <li><tt>s</tt> (PCRE_DOTALL) – the <tt>.</tt> metacharacter
* matches newline as well.</li>
* <li><tt>u</tt> (Unicode mode) – the meaning of
* character class escape sequences <tt>\b</tt>, <tt>\w</tt>,
* and <tt>\W</tt> is extended to include Unicode character
* properties.</li>
* <li><tt>x</tt> (PCRE_EXTENDED) – whitespace within
* the pattern is ignored, so that it is easier
* human-readable.</li>
* </ul><p>
* Flags except for Unicode mode can be set and unset for
* parts of the expression outside of character classes using
* the <tt>(?…)</tt> and <tt>(?-…)</tt> notations.
* </li>
* <li>Unicode property classes using e.g. the \p{…} notation</li>
* <li>Named capturing groups by passing strings with the
* <tt>(?P<name>…)</tt> or <tt>(?P'name'…)</tt> notation,
* where the <tt>P</tt> is optional, respectively.</li>
* </ul><p>
* This is facilitated through the following steps:
* </p><ol>
* <li>The flags <code>x</code>, <code>s</code> and <code>u</code>
* in the optional <var>sFlags</var> argument set the initial
* state of the pattern-match modifiers; the extended
* {@link RegExp}'s <code>extended</code>, <code>dotAll</code>,
* and <code>unicodeMode</code> properties are set accordingly.
* These flags are removed from the <var>sFlags</var>
* argument subsequently, as it is reused to create the
* {@link RegExp} instance. [Conforming implementations of
* ECMA-262 Ed. 5.1 MUST throw a <code>SyntaxError</code>
* exception on flags other than <code>g</code>, <code>i</code>,
* and <code>m</code> (section 15.10.4.1); implementations of
* Ed. 6.0 and later may also support the <code>u</code>
* (Unicode) and <code>y</code> (sticky) flags,
* but nothing else. Note that as of Ed. 8.0 the <em>standard</em>
* <code>u</code> flag does not provide support for Unicode character
* properties.]</li>
* <li>The pattern is run through several passes, where in each
* one it is scanned from left to right using another
* {@link RegExp}:
* <ol style="margin-bottom: 1em; list-style-type: lower-roman">
* <li><p>Capturing groups and pattern-match modifiers in the
* pattern are matched and replaced.
* <p>Capturing groups are replaced with the opening
* parenthesis if they were assigned a name. The
* extended {@link RegExp}'s <code>groups</code>,
* <code>names</code>, and <code>_patternGroups</code>
* properties are set accordingly. They are used in an
* overwritten <code>exec()</code> method and when matching
* against a <code>jsx.regexp.String</code> using its
* <tt>match(…)</tt> method.</p>
* <p style="margin-bottom: 0">
* Pattern-match modifiers are set and unset as they
* are scanned. The corresponding substrings are
* removed from the pattern. If the group is otherwise
* empty, and therefore is not a group at all,
* the entire pseudo-group is removed.</p>
* <ol style="margin-top: 0; list-style-type: lower-latin">
* <li>With PCRE_EXTENDED set, single-line
* comments starting with <tt>#</tt> and unescaped
* whitespace are removed from the pattern. The backslash
* is removed from the pattern when in front of
* whitespace.</li>
* <li>With PCRE_DOTALL set, unescaped <tt>.</tt>
* (period) characters are replaced with the character class
* <tt>[\S\s]</tt> which matches all Unicode characters.</li>
* </ol>
* <p><em>NOTE: Unlike in Perl and PCRE, a pattern-match
* modifier affects all of the pattern that follows,
* even outside the group in which the modifier was
* set/unset. This will be fixed in a later version.</em>
* </p></li>
* <li>When in Unicode mode,
* <ol style="list-style-type: lower-latin">
* <li>in the second pass, character class escape sequences
* <tt>\w</tt> and <tt>\W</tt> are replaced with
* corresponding uses of <tt>\p{Word}</tt>.</li>
* <li>in the third pass, <tt>\b</tt> is replaced with
* corresponding uses of character classes and negative
* lookahead.
* </ol></li>
* <li style="margin-top: 1em">The <tt>\p{…}</tt> and <tt>\P{…}</tt>
* escape sequences are replaced with the corresponding
* character classes.</li>
* </ol></li>
* <li>The resulting expression and remaining flags are passed
* to the {@link RegExp} constructor.</li>
* <li>The created {@link RegExp} instance is augmented with
* properties and returned.</li>
* </ol><p>
* There are the following possibilities to make Unicode property
* classes known to this constructor:
* </p><ol>
* <li>Provide the Unicode Character Database, or parts thereof,
* as an Object;</li>
* <li>Provide the Unicode Character Database, or parts thereof,
* as a plain text resource that is accessed with
* XMLHttpRequest;</li>
* <li>Define property classes manually</li>
* </ol>
* <p>
* Variant #1 requires you to define a mapping object with
* the following namespace and structure:
* </p>
* <pre><code>
* jsx.regexp.RegExp.propertyClasses = {
* ...,
* Sc: "\u20AC...",
* ...
* };
* </code></pre>
* <p>
* The property name is the name of the Unicode property class
* (here: <tt>Sc</tt>). The property value (a string) defines
* which characters belong to that class. You may use "-"
* to specify character ranges, i.e., the range of characters
* including the characters having the boundaries as code point
* value, and all characters that have a code point value
* in-between. (For a literal "-", you may use "\\-".)
* An example file to mirror the Unicode 5.0 Character Database,
* UnicodeData.js, is distributed with this file. Include it
* <em>after</em> the file that declares the constructor (this
* file) to use it. If you do not include it, but use the
* <code>\p{...}</code> notation, an attempt will be made to load
* the file specified by the <code>ucdScriptPath</code> property
* (default: <code>"/scripts/UnicodeData.js"</code>) using
* synchronous XHR (see below).
* </p>
* <p>
* Variant #2 is going to support two different methods:
* Synchronous and asynchronous request-response handling.
* Synchronous request-response handling requests the (partial)
* Unicode Character Database from the resource specified by
* the <code>ucdTextPath</code> property (default:
* <code>"/scripts/UnicodeData.txt"</code>) and halts execution
* until a response has been received or the connection timed out.
* Asynchronous request-response handling allows script execution
* to continue while the request and response are in progress, but
* you need to provide a callback as third argument where actions
* related to the regular expression must be performed.
* Asynchronous handling is recommended for applications that need
* to be responsive to user input. <strong>Currently, only
* synchronous handling is implemented.</strong>
* </p>
* <p>
* Variant #3 can be combined with the other variants.
* The constructor has a definePropertyClasses() method which can
* be used to define and redefine property classes. This allows
* an extended RegExp object to support only a subset of Unicode
* property classes, and to support user-defined character
* property classes.
* </p>
*
* The returned {@link RegExp} has additional properties to
* accomodate syntax extensions in the pattern string:
*
* @constructor
* @param {String|RegExp} expression
* A regular expression pattern string that may use the features
* described above. If it is a {@link RegExp}, its
* <code>source</code> property is used and combined with
* <var>sFlags</var>. That is, <code>jsx.regexp.RegExp(/foo/, "i")</code>
* returns the same as <code>jsx.regexp.RegExp(/foo/i)</code>.
* @param {String} sFlags
* Optional string containing none, one or more of the standard
* {@link RegExp} modifiers and the flags described above.
* Unsupported flags are ignored, but passed on to {@link RegExp}.
* Note that modifiers in <var>expression</var> can temporarily
* unset and set the "s" and "x" flags. Following Perl, the "u"
* flag (Unicode mode) can only be enabled, but not disabled.
* @return {RegExp}
* A regular expression with the property class escape sequences
* expanded according to the specified data, with the specified
* flags set if they are natively supported.
*/
function jsx_regexp_RegExp (expression, sFlags)
{
var flags = _getDataObject();
var flagsMap = _getDataObject({
g: "global",
i: "ignoreCase",
m: "multiline",
y: "sticky"
});
var flagsMapKeys = _getKeys(flagsMap);
var sExpressionFlags = "";
if (expression && _getClass(expression) == "RegExp")
{
for (var i = 0, len = flagsMapKeys.length; i < len; ++i)
{
var key = flagsMapKeys[i];
var expressionFlag = !!expression[flagsMap[key]];
flags[flagsMap[key]] = expressionFlag;
if (expressionFlag) sExpressionFlags += key;
}
expression = expression.source;
}
var t = typeof expression;
if (t != "string")
{
if (arguments.length < 1)
{
expression = "";
}
else
{
expression = String(expression);
}
}
var pattern = expression;
if (typeof sFlags == "undefined")
{
sFlags = sExpressionFlags;
}
else
{
for (i = 0, len = flagsMapKeys.length; i < len; ++i)
{
flags[flagsMap[flagsMapKeys[i]]] = (sFlags.indexOf(flagsMapKeys[i]) > -1);
}
}
var extended = false;
var dotAll = false;
var unicodeMode = false;
if (sFlags)
{
if (sFlags.indexOf("x") > -1)
{
var originalExtended = extended = true;
}
if (sFlags.indexOf("s") > -1)
{
var originalDotAll = dotAll = true;
}
if (sFlags.indexOf("u") > -1)
{
unicodeMode = true;
}
sFlags = sFlags.replace(/[xs]/g, "");
if (unicodeMode && !_beyondBMPsupport)
{
sFlags = sFlags.replace(/u/g, "");
}
}
_extend(flags, {
extended: !!originalExtended,
dotAll: !!originalDotAll,
unicodeMode: unicodeMode
}, _ADD_OVERWRITE);
/* Support for capturing and special groups */
var groupCount = 0;
var groups = _getDataObject();
var names = _getDataObject();
var patternGroups = [expression];
/*jshint -W072*/
expression = expression.replace(
/(\\\()/.concat(
"|",
/(\((\?P?(([adlupimsx]+)?(-([imsx]+))?)(<([^>]+)>|'([^']+)'|([:!]))?(\))?)?)/g,
"|",
/(#.*(\r?\n|\r|$))|\\(\s)/,
"|",
/\[([^\\\]]|\\.)*\]|(\s+)|\\\.|(\.)/g
),
function (match, escapedLParen,
group, specialGroup, modifierGroup,
positiveModifiers, negativeModifiers_opt, negativeModifiers,
namedGroup, bracketedName, quotedName,
nonCapturingGroup, emptyGroup,
comment, newline,
escapedWS, charClassContent, whitespace,
plainDot,
index, all) {
if (group)
{
var capturingGroup = (!nonCapturingGroup && !(modifierGroup && emptyGroup));
if (capturingGroup) ++groupCount;
if (positiveModifiers)
{
var
rxPosModifiers = /[sx]/g,
m;
while ((m = rxPosModifiers.exec(positiveModifiers)))
{
switch (m[0])
{
case "s":
dotAll = true;
break;
case "x":
extended = true;
}
}
}
if (negativeModifiers)
{
var rxNegModifiers = /[sx]/g;
while ((m = rxNegModifiers.exec(negativeModifiers)))
{
switch (m[0])
{
case "s":
dotAll = false;
break;
case "x":
extended = false;
}
}
}
if (capturingGroup)
{
/* Support for named capturing groups (PCRE-compliant) */
var name = bracketedName || quotedName;
if (name)
{
if (names[name])
{
jsx.throwThis("SyntaxError", "Duplicate symbolic name");
}
groups[groupCount] = name;
names[name] = groupCount;
}
/*
* NOTE: Helps with determining in exec() and match()
* whether \b matched at beginning and \Ws need to be
* ltrimmed from match
*/
patternGroups.push(all.substring(index));
return "(";
}
return (emptyGroup ? "" : "(?" + nonCapturingGroup);
}
/* PCRE_EXTENDED */
if (extended)
{
/* Remove comments */
if (comment) return "";
/* Keep escaped whitespace, remove escape */
if (escapedWS) return escapedWS;
/* Remove unescaped whitespace */
if (whitespace) return "";
}
/* PCRE_DOTALL */
if (dotAll && plainDot) return "[\\S\\s]";
return match;
});
/*jshint +W072*/
groups.length = groupCount;
/* Unicode mode */
if (unicodeMode)
{
var characterEscapes = {
"d": "\\p{Digit}",
"s": "\\p{Space}",
"w": "\\p{Word}"
};
expression = expression.replace(
/\[(([^\]\\]|\\.)*)\]|(\\([dsw]))/gi,
function (match, charClassContent, p2, classCharacter, escapeLetter) {
if (charClassContent)
{
/* Do not expand PCRE_DOTALL expansion */
/* TODO: Never expand all-inclusive character classes */
if (charClassContent == "\\S\\s")
{
return "[" + charClassContent + "]";
}
var normalized = _normalizeCharClass(charClassContent, true);
return normalized.replace(
/\\\\|\\([dsw])/gi,
function (match, escapeLetter) {
if (escapeLetter)
{
return characterEscapes[escapeLetter.toLowerCase()];
}
return match;
});
}
if (classCharacter)
{
return "["
+ (escapeLetter >= "A" && escapeLetter <= "Z" ? "^" : "")
+ characterEscapes[escapeLetter.toLowerCase()] + "]";
}
return match;
});
/* Replace \b */
var firstGroup = expression.match(/\((\?(P?(<([^>]+)>|'([^']+)')|[:!]))?/);
var afterFirstGroup = (firstGroup && (firstGroup.index + firstGroup[0].length) || 0);
var wordEscape = characterEscapes.w;
expression = expression.replace(
/\\\\|(\\b)/g,
function (match, wordBorder, index, all) {
if (wordBorder)
{
/* Handle \b in leading groups properly */
if (index > afterFirstGroup)
{
return "(?!" + wordEscape + ")";
}
return "(?:^|[^" + wordEscape + "])";
}
return match;
});
}
/* Support for Unicode character property classes (PCRE-compliant) */
expression = expression.replace(rxEscapes, fEscapeMapper);
var rx = new RegExp(expression, sFlags);
/* Augmented properties */
rx.pattern = pattern;
rx._patternGroups = patternGroups;
rx.groups = groups;
rx.names = names;
rx._flags = flags;
rx.dotAll = !!originalDotAll;
rx.extended = !!originalExtended;
rx.unicodeMode = unicodeMode;
rx._oldExec = rx.exec;
rx.exec = jsx_regexp_RegExp.exec;
return rx;
}
return jsx_regexp_RegExp;
}()
),
{
/**
* @memberOf jsx.regexp.RegExp
*/
ucdScriptPath: "/scripts/UnicodeData.js",
ucdTextPath: "/scripts/UnicodeData.txt",
/**
* Determines if an object has been constructed using this constructor.
*
* @param rx
* @return {boolean}
*/
isInstance: function (rx) {
return !!rx.pattern;
},
/**
* @function
*/
exec: (function () {
var rx2;
/**
* @param {string} s
* @param {jsx.regexp.RegExp} rx
* @return {Object|null}
* @see RegExp.prototype.exec()
*/
function _exec (s, rx)
{
/* NOTE: Use passed expression only when called statically */
if (_getClass(this) == "RegExp") rx = this;
rx._realExec = (rx._oldExec || rx.exec);
var matches = rx._realExec(s);
if (matches && _RegExp2.isInstance(rx))
{
matches.groups = _getDataObject();
if (rx.unicodeMode && !rx2)
{
rx2 = new _RegExp2("^\\W+", "u");
}
for (var i = 0, len = matches.length; i < len; ++i)
{
/* Trim leading \b matches */
var patternGroup = rx._patternGroups[i];
if (rx.unicodeMode
&& patternGroup
&& patternGroup.match(
/^(\((\?P?(<([^>]+)>|'([^']+)'))?)*\\b/))
{
matches[i] = matches[i].replace(rx2, "");
}
matches.groups[rx.groups[i] || i] = matches[i];
}
}
return matches;
}
return _exec;
}()),
/**
* (Re-)defines one or more property classes.
*
* @param {Object} o
* Object whose own enumerable properties are used
* for property class definitions
* @return {jsx.regexp.RegExp}
* This object
*/
definePropertyClasses: function (o) {
for (var keys = _jsx_object.getKeys(o), i = 0, len = keys.length;
i < len; ++i)
{
var p = keys[i];
this.propertyClasses[p] = o[p];
}
return this;
},
/**
* Deletes a property class.
*
* @param {String} p
* @return {boolean}
* <code>true</code> if successful, <code>false</code> otherwise.
*/
deletePropertyClass: function (p) {
return (delete this.propertyClasses[p]);