forked from amobiz/regexgen.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1541 lines (1363 loc) · 39.2 KB
/
index.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
/* eslint-env node, browser */
/*!
* RegexGen.js - JavaScript Regular Expression Generator v0.3.0
* https://github.com/amobiz/regexgen.js
*
* Supports CommonJS(node.js).
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
* Date: 2014-06-11
* Update: 2015-12-19
*/
/**
* @fileOverview RegexGen.js is a JavaScript regular expression generator
* that helps to construct complex regular expressions.
* @author Amobiz([email protected])
* @version 0.2.0
* @license MIT
*
*/
'use strict';
////////////////////////////////////////////////////
var regexCodes = {
captureParentheses: /(\((?!\?[:=!]))/g,
characterClassChars: /^(?:.|\\[bdDfnrsStvwW]|\\x[A-Fa-f0-9]{2}|\\u[A-Fa-f0-9]{4}|\\c[A-Z])$/,
characterClassExpr: /^\[\^?(.*)]$/,
ctrlChars: /^[A-Za-z]$/,
hexAsciiCodes: /^[0-9A-Fa-f]{2}$/,
hexUnicodes: /^[0-9A-Fa-f]{4}$/,
//
// Regular Expressions
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
// metaChars: /([.*+?^=!:${}()|\[\]\/\\])/g,
//
// How to escape regular expression in javascript?
// http://stackoverflow.com/questions/2593637/how-to-escape-regular-expression-in-javascript
// answerd by Gracenotes
// metaChars: /([.?*+^$[\]\\(){}|-])/g,
//
// using Gracenotes version plus '\/'.
// note that MDN's version includes: ':', '=', '!' and '-',
// they are metacharacters only when used in (?:), (?=), (?!) and [0-9] (character classes), respectively.
// metaChars: /([.?*+^$[\]\/\\(){}|-])/g,
//
// According to the book Regular Expression Cookbook
// (added '/' for convenience when using the /regex/ literal):
//
metaChars: /([$()*+.?[\\^{|\/])/g,
//
// What literal characters should be escaped in a regex? (corner cases)
// http://stackoverflow.com/questions/5484084/what-literal-characters-should-be-escaped-in-a-regex
//
// How to escape square brackets inside brackets in grep
// http://stackoverflow.com/questions/21635126/how-to-escape-square-brackets-inside-brackets-in-grep?rq=1
//
metaClassChars: /([-\]\\^])/g,
// treat any single character, meta characters, character classes, back reference, unicode character, ascii character,
// control character and special escaped character in regular expression as a unit term.
unitTerms: /^(?:.|\\[bBdDfnrsStvwW]|\\x[A-Fa-f0-9]{2}|\\u[A-Fa-f0-9]{4}|\\c[A-Z]|\\[$()*+.?[\/\\^{|]|\[(?:\\\]|[^\]])*?\]|\\\d{1,2})$/
};
var zeropad = '00000000';
////////////////////////////////////////////////////////
// regexGen
////////////////////////////////////////////////////////
/**
* The Generator
* =============
*
* The generator is exported as the `regexGen()` function, everything must be referenced from it.
*
* To generate a regular expression, pass sub-expressions as parameters to the call of `regexGen()` function.
*
* Sub-expressions are then concatenated together to form a whole regular expression.
*
* Sub-expressions can either be a `string`, a `number`, a `RegExp` object,
* or any combinations of the call to methods (i.e., the `sub-generators`) of the `regexGen()` function object.
*
* Strings passed to the the call of `regexGen()`, `text()`, `maybe()`, `many()`, `any()`, `anyCharOf()`
* and `anyCharBut()` functions, are always escaped as necessary,
* so you don't have to worry about which characters to escape.
*
* The result of calling the `regexGen()` function is a `RegExp` object.
* See __<a href="#user-content-the-regexp-object">The RegExp Object</a>__ section for detail.
*
* Since everything must be referenced from the `regexGen()` function,
* to simplify codes, assign it to a short variable is preferable.
*
* @example
* var _ = regexGen;
*
* var regex = regexGen(
* _.startOfLine(),
* _.capture( 'http', _.maybe( 's' ) ), '://',
* _.capture( _.anyCharBut( ':/' ).repeat() ),
* _.group( ':', _.capture( _.digital().multiple(2,4) ) ).maybe(), '/',
* _.capture( _.anything() ),
* _.endOfLine()
* );
* var matches = regex.exec( url );
*
* @namespace regexGen
* @returns {RegExp} the generated RegExp object.
*/
function regexGen() {
var i, n, context, term, terms, pattern, modifiers, regex;
terms = [];
modifiers = [];
context = {
captures: ['0'],
warnings: []
};
for (i = 0, n = arguments.length; i < n; ++i) {
term = arguments[i];
if (term instanceof Modifier) {
if (modifiers.indexOf(term._modifier) !== -1) {
context.warnings.push('duplicated modifier: ' + term._modifier);
continue;
}
modifiers.push(term._modifier);
} else {
terms.push(term);
}
}
pattern = new Sequence(terms)._generate(context, 0);
regex = new RegExp(pattern, modifiers.join(''));
_mixin(regex, {
warnings: context.warnings,
captures: context.captures,
extract: extract,
replace: replace
});
return regex;
}
////////////////////////////////////////////////////////
function extract(text) {
var self = this;
var json, all;
if (self.global) {
self.lastIndex = 0;
all = [];
while ((json = extractor())) {
all.push(json);
}
return all;
}
return extractor();
function extractor() {
var results;
results = self.exec(text);
return _capturesToJson(self.captures, results);
}
}
/**
* This method returns a new string with some or all matches of a pattern replaced by a pre-defined replacement.
* The replacement can be a string or a function to be called for each match.
*
* @param {String} text - the string being examined.
* @param {String | Function} replacement - the string or function that replaces the substring matched.
* The function should be of the `function(matches, offset, text)` signature.
* @returns {String} a new string with some or all matches of a pattern replaced by a replacement.
*
* @example
* var _ = regexGen;
* var regex = regexGen(
* _.capture( _.label('temp'),
* _.digital().many(),
* _.maybe(
* '.',
* _.digital().many()
* )
* ),
* 'F'
* );
* regex.replace("The temp is 11.3F.", "${temp} degree in Fahrenheit");
* regex.replace("The temp is 11.3F.", function(matches, offset, string) {
* return ((matches.temp - 32) * 5/9) + 'C';
* });
*
*/
function replace(text, replacement) {
var varRegex = /\${([^}]+)}/g;
var self = this;
var replacementCache;
if (typeof replacement === 'string') {
if (!self._replacementCache) {
self._replacementCache = {};
}
replacementCache = self._replacementCache;
if (!replacementCache[replacement]) {
replacementCache[replacement] = replacement.replace(varRegex, function (matches, variable) {
var idx;
idx = self.captures.indexOf(variable);
return idx === -1 ? matches : '$' + idx;
});
}
return text.replace(self, replacementCache[replacement]);
} else if (typeof replacement === 'function') {
return text.replace(self, replacer);
}
return text;
function replacer() {
var offset, string, json;
offset = arguments[arguments.length - 2];
string = arguments[arguments.length - 1];
json = _capturesToJson(self.captures, arguments);
return replacement(json, offset, string);
}
}
function _capturesToJson(captures, values) {
var i, n, json;
if (!values) {
return null;
}
json = {};
for (i = 1, n = captures.length; i < n; ++i) {
json[captures[i]] = values[i];
}
return json;
}
////////////////////////////////////////////////////////
function _mixin(obj) {
var i, k, ext;
for (i = 1; i < arguments.length; ++i) {
ext = arguments[i];
for (k in ext) {
if (ext.hasOwnProperty(k)) {
obj[k] = ext[k];
}
}
}
return obj;
}
////////////////////////////////////////////////////////
function toHex(value, digits) {
var ret;
ret = value.toString(16);
if (ret.length < digits) {
return zeropad.substring(0, digits - ret.length) + ret;
}
return ret;
}
function isArray(o) {
return (Object.prototype.toString.call(o) === '[object Array]');
}
////////////////////////////////////////////////////////
_mixin(regexGen, {
/**
* A utility function helps using the regexGen generator.
* @memberof regexGen
* @param {Object} global - the target object that sub-generators will inject to.
*/
mixin: function (global) {
_mixin(global, regexGen);
},
////////////////////////////////////////////////////
// Modifiers
////////////////////////////////////////////////////
/**
* Case-insensitivity modifier.
* @memberof regexGen
* @static
*/
ignoreCase: function () {
return new Modifier('i');
},
/**
* Default behaviour is with "g" modifier,
* so we can turn this another way around
* than other modifiers
* @memberof regexGen
* @static
*/
searchAll: function () {
return new Modifier('g');
},
/**
* Multiline
* @memberof regexGen
* @static
*/
searchMultiLine: function () {
return new Modifier('m');
},
////////////////////////////////////////////////////
// Boundaries
////////////////////////////////////////////////////
/**
* @memberof regexGen
* @returns {Term}
*/
startOfLine: function () {
return new Term('^');
},
/**
* @memberof regexGen
* @returns {Term}
*/
endOfLine: function () {
return new Term('$');
},
/**
* Matches a word boundary. A word boundary matches the position
* where a word character is not followed or preceeded by another word-character.
* Note that a matched word boundary is not included in the match.
* In other words, the length of a matched word boundary is zero.
* (Not to be confused with [\b].)
*
* @memberof regexGen
* @static
* @returns {Term} the word boundary expression term object.
*/
wordBoundary: function () {
return new Term('\\b');
},
/**
* Matches a non-word boundary.
* This matches a position where the previous and next character
* are of the same type: Either both must be words, or both must be non-words.
* The beginning and end of a string are considered non-words.
*
* @memberof regexGen
* @static
* @returns {Term} the non-word boundary expression term object.
*/
nonWordBoundary: function () {
return new Term('\\B');
},
////////////////////////////////////////////////////
// Literal Characters
////////////////////////////////////////////////////
/**
* Any character sequence (abc).
* @memberof regexGen
* @param {String} value the character sequence.
* @returns {Term} the text literal expression term object.
*/
text: function (value) {
return Term.sanitize(value);
},
////////////////////////////////////////////////////
// Character Classes
////////////////////////////////////////////////////
/**
* Any given character ([abc])
* usage: anyCharOf( [ 'a', 'c' ], ['2', '6'], 'fgh', 'z' ): ([a-c2-6fghz])
* @memberof regexGen
* @returns {Term}
*/
anyCharOf: function () {
var warnings;
warnings = [];
return new Term('[' + Term.charClasses(arguments, true, warnings) + ']')._warn(warnings);
},
/**
* Anything but these characters ([^abc])
* usage: anyCharBut( [ 'a', 'c' ], ['2', '6'], 'fgh', 'z' ): ([^a-c2-6fghz])
* @memberof regexGen
* @returns {Term}
*/
anyCharBut: function () {
var warnings;
warnings = [];
return new Term('[^' + Term.charClasses(arguments, false, warnings) + ']')._warn(warnings);
},
////////////////////////////////////////////////////
// Character Shorthands
////////////////////////////////////////////////////
/**
* Matches any single character except the newline character (.)
* @memberof regexGen
* @returns {Term}
*/
anyChar: function () {
return new Term('.');
},
/**
* Matches the character with the code hh (two hexadecimal digits)
* @memberof regexGen
* @returns {Term}
*/
ascii: function () {
var i, n, value, values, warning;
values = '';
warning = [];
n = arguments.length;
if (n > 0) {
for (i = 0; i < n; ++i) {
value = arguments[i];
if (typeof value === 'string' && regexCodes.hexAsciiCodes.test(value)) {
values += '\\x' + value;
continue;
} else if (typeof value === 'number' && (0 <= value && value <= 0xFF)) {
values += '\\x' + toHex(value, 2);
continue;
}
warning.push(value.toString());
}
return new Term(values)._warn(warning.length === 0 ? '' : 'ascii(): values are not valid 2 hex digitals ascii code(s): ', warning);
}
return new Term()._warn('ascii(): no values given, should provides a 2 hex digitals ascii code or any number <= 0xFF.');
},
/**
* Matches the character with the code hhhh (four hexadecimal digits).
* @memberof regexGen
* @returns {Term}
*/
unicode: function () {
var i, n, value, values, warning;
values = '';
warning = [];
n = arguments.length;
if (n > 0) {
for (i = 0, n = arguments.length; i < n; ++i) {
value = arguments[i];
if (typeof value === 'string' && regexCodes.hexUnicodes.test(value)) {
values += '\\u' + value;
continue;
} else if (typeof value === 'number' && (0 <= value && value <= 0xFFFF)) {
values += '\\u' + toHex(value, 4);
continue;
}
warning.push(value.toString());
}
return new Term(values)._warn(warning.length === 0 ? '' : 'unicode(): values are not valid 2 hex digitals unicode code(s): ', warning);
}
return new Term()._warn('unicode(): no values given, should provides a 2 hex digitals ascii code or any number <= 0xFFFF.');
},
/**
* Matches a NULL (U+0000) character.
* Do not follow this with another digit,
* because \0<digits> is an octal escape sequence.
* @memberof regexGen
* @returns {Term}
*/
nullChar: function () {
return new Term('\\0');
},
/**
* Matches a control character in a string.
* Where X is a character ranging from A to Z.
* @memberof regexGen
* @returns {Term}
*/
controlChar: function (value) {
if (typeof value === 'string' && regexCodes.ctrlChars.test(value)) {
return new Term('\\c' + value);
}
return new Term()._warn('controlChar(): specified character is not a valid control character: ', value);
},
/**
* Matches a backspace (U+0008).
* You need to use square brackets if you want to match a literal backspace character.
* (Not to be confused with \b.)
* @memberof regexGen
* @returns {Term}
*/
backspace: function () {
return new Term('[\\b]');
},
/**
* Matches a form feed: (\f)
* @memberof regexGen
* @returns {Term}
*/
formFeed: function () {
return new Term('\\f');
},
/**
* Matches a line feed: (\n)
* @memberof regexGen
* @returns {Term}
*/
lineFeed: function () {
return new Term('\\n');
},
/**
* Matches a carriage return: (\r)
* @memberof regexGen
* @returns {Term}
*/
carriageReturn: function () {
return new Term('\\r');
},
/**
* Matches a single white space character, including space, tab, form feed, line feed: (\s)
* @memberof regexGen
* @returns {Term}
*/
space: function () {
return new Term('\\s');
},
/**
* Matches a single character other than white space: (\S)
* @memberof regexGen
* @returns {Term}
*/
nonSpace: function () {
return new Term('\\S');
},
/**
* Matches a tab (U+0009): (\t)
* @memberof regexGen
* @returns {Term}
*/
tab: function () {
return new Term('\\t');
},
/**
* Matches a vertical tab (U+000B): (\s)
* @memberof regexGen
* @returns {Term}
*/
vertTab: function () {
return new Term('\\v');
},
/**
* Matches a digit character: (\d)
* @memberof regexGen
* @returns {Term}
*/
digital: function () {
return new Term('\\d');
},
/**
* Matches any non-digit character
* @memberof regexGen
* @returns {Term}
*/
nonDigital: function () {
return new Term('\\D');
},
/**
* Matches any alphanumeric character including the underscore: (\w)
* @memberof regexGen
* @returns {Term}
*/
word: function () {
return new Term('\\w');
},
/**
* Matches any non-word character.
* @memberof regexGen
* @returns {Term}
*/
nonWord: function () {
return new Term('\\W');
},
////////////////////////////////////////////////////
// Extended Character Shorthands
////////////////////////////////////////////////////
/**
* Matches any characters except the newline character: (.*)
* @memberof regexGen
* @returns {Term}
*/
anything: function () {
return new Term('.', '*');
},
/**
* @memberof regexGen
* @returns {Term}
*/
hexDigital: function () {
return new Term('[0-9A-Fa-f]');
},
/**
* Matches any line break, includes Unix and windows CRLF
* @memberof regexGen
* @returns {Term}
*/
lineBreak: function () {
return this.either(this.group(this.carriageReturn(), this.lineFeed()),
this.carriageReturn(),
this.lineFeed()
);
},
/**
* Matches any alphanumeric character sequence including the underscore: (\w+)
* @memberof regexGen
* @returns {Term}
*/
words: function () {
return new Term('\\w', '+');
},
////////////////////////////////////////////////////
// Quantifiers
////////////////////////////////////////////////////
/**
* @memberof regexGen
* @returns {Term}
*/
any: function (value) {
return Term.sanitize(value, '*');
},
/**
* occurs one or more times (x+)
* @memberof regexGen
* @returns {Term}
*/
many: function (value) {
return Term.sanitize(value, '+');
},
/**
* Any optional character sequence, shortcut for Term.maybe ((?:abc)?)
* @memberof regexGen
* @returns {Term}
*/
maybe: function (value) {
return Term.sanitize(value, '?');
},
////////////////////////////////////////////////////
// Grouping and back references
////////////////////////////////////////////////////
/**
* Adds alternative expressions
* @memberof regexGen
* @returns {Sequence}
*/
either: function () {
return new Sequence(arguments, '', '', '|')._warn(
arguments.length >= 2 ? '' : 'eidther(): this function needs at least 2 sub-expressions. given only: ', arguments[0]
);
},
/**
* Matches specified terms but does not remember the match. The generated parentheses are called non-capturing parentheses.
* @memberof regexGen
* @returns {Sequence}
*/
group: function () {
return new Sequence(arguments);
},
/**
* Matches specified terms and remembers the match. The generated parentheses are called capturing parentheses.
* label 是用來供 back reference 索引 capture 的編號。
* 計算方式是由左至右,計算左括號出現的順序,也就是先深後廣搜尋。
* capture( label('cap1'), capture( label('cap2'), 'xxx' ), capture( label('cap3'), '...' ), 'something else' )
* @memberof regexGen
* @returns {Capture}
*/
capture: function () {
var label, sequence;
if (arguments.length > 0 && arguments[0] instanceof Label) {
label = arguments[0]._label;
sequence = Array.prototype.slice.call(arguments, 1);
} else {
label = '';
sequence = arguments;
}
return new Capture(label, sequence);
},
/**
* label is a reference to a capture group, and is allowed only in the capture() method
* @memberof regexGen
* @returns {Label}
*/
label: function (label) {
return new Label(label);
},
/**
* back reference
* @memberof regexGen
* @returns {CaptureReference}
*/
sameAs: function (label) {
return new CaptureReference(label);
},
////////////////////////////////////////////////////
/**
* trust me, just put the value as is.
* @memberof regexGen
* @returns {Term | RegexOverwrite}
*/
regex: function (value) {
if (value instanceof RegExp) {
return new RegexOverwrite(value.source);
} else if (typeof value === 'string') {
return new RegexOverwrite(value);
}
return new Term(value)._warn('regex(): specified regex is not a RegExp instance or is not a string: ', value);
}
});
////////////////////////////////////////////////////////
// Term
////////////////////////////////////////////////////////
/**
* Construct a Term object.
*
* The Term object represents a valid fragment of regular expression
* that forms a small part of the whole regular expression.
*
* @class Term
* @protected
* @param {Object} body - a valid regular expression unit.
* @param {String} quantifiers - the quantifiers applied on this term.
*/
function Term(body, quantifiers) {
this._init(body, quantifiers);
}
_mixin(Term, /** @lends Term */ {
/**
* Quote regular expression characters.
*
* Takes string and puts a backslash in front of every character that is part of the regular expression syntax.
*
* @static
* @protected
* @param {String} value - the string to quote.
* @returns {String} the quoted string.
*/
quote: function (value) {
return value.replace(regexCodes.metaChars, '\\$1');
},
/**
* Quote the terms so they can be put into character classes (square brackets).
*
* @static
* @protected
* @param {Array} list - the input term(s) to convert.
* @param {Boolean} positive - treat for positive or negative character classes.
* @param {Array} warnings - [output] a collection array to keep errors / warnings while converting character classes.
* @returns a single character sequence that can fit into character classes.
*/
charClasses: function (list, positive, warnings) {
var i, v, sets, value, hyphen, circumflex;
hyphen = circumflex = '';
sets = [];
for (i = 0; i < list.length; ++i) {
v = list[i];
v = range(v) || chars(v) || term(v);
if (v) {
sets.push(v);
} else {
warnings.push('invalid character: ' + v);
}
}
value = sets.join('');
if (value) {
return (hyphen + value + circumflex);
}
value = hyphen + circumflex;
if (value.length === 1 && positive) {
return Term.quote(value);
}
return value;
function range(pair) {
if (isArray(pair)) {
if ((pair.length === 2 &&
((typeof pair[0] === 'number' && (0 <= pair[0] && pair[0] <= 9)) || (typeof pair[0] === 'string' && regexCodes.characterClassChars.test(pair[0]))) &&
((typeof pair[1] === 'number' && (0 <= pair[1] && pair[1] <= 9)) || (typeof pair[1] === 'string' && regexCodes.characterClassChars.test(pair[1]))))) {
return pair[0] + '-' + pair[1];
}
}
}
// bunch of characters
function chars(c) {
var s;
if (typeof c === 'string') {
s = c;
if (s.indexOf('-') !== -1) {
hyphen = '-';
s = s.replace(/-/g, '');
}
if (s.indexOf('^') !== -1) {
circumflex = '^';
s = s.replace(/\^/g, '');
}
return s.replace(regexCodes.metaClassChars, '\\$1');
}
}
function term(t) {
var match, result;
if (t instanceof Term) {
if (t._quantifiers) {
warnings.push('ignoring quantifier of embeded character class: ' + t._quantifiers);
}
if (t._preLookaheads || t._lookaheads) {
warnings.push('ignoring lookaheads of embeded character class: ' + t._preLookaheads + ' : ' + t._lookaheads);
}
match = t._body.match(regexCodes.characterClassExpr);
if (match && match[1]) {
result = match[1];
if (match[0] === '^') {
warnings.push('ignoring negation directive of embeded character class');
result = result.substring(1);
}
return result;
} else if (regexCodes.characterClassChars.test(t._body)) {
return t._body;
}
}
}
},
/**
* Sanitation function for adding anything safely to the expression.
*
* @static
* @protected
* @param {Object} body - the expression object to sanitize.
* @param {String} quantifiers - the quantifiers applied on this term.
* @returns {Term} a new Term object with contents sanitized.
*/
sanitize: function (body, quantifiers) {
if (body instanceof Term) {
return body;
} else if (typeof body === 'string') {
return new Term(Term.quote(body), quantifiers);
} else if (typeof body === 'number') {
return new Term(body.toString(), quantifiers);
} else if (body instanceof RegExp) {
return new RegexOverwrite(body.source);
}
return new Term()._warn('invalid regular expression: ', body);
},
/**
* Test if the given expression is a unit term.
*
* @static
* @protected
* @param {String} expression - the expression string to test.
* @returns {Boolean} true is the given expression is a unit term.
*/
isUnitTerm: function (expression) {
return regexCodes.unitTerms.test(expression);
},
/**
* Wrap the given expression if it is not a unit term.
*
* @static
* @protected
* @param {String} body - the expression string to test.
* @returns {String} a unit expression that is properly protected.
*/
wrap: function (body) {
if (Term.isUnitTerm(body)) {
return body;
}
return '(?:' + body + ')';
}
});
////////////////////////////////////////////////////
_mixin(Term.prototype, /** @lends Term.prototype */ {
/**
* Initialize the term object, setup default values.
*
* @protected
* @param {String} body - the expression string.
* @param {String} quantifiers - the quantifiers applied on this term.
*/
_init: function (body, quantifiers) {
this._body = body || '';
this._quantifiers = quantifiers || '';
this._greedy = '';
this._preLookaheads = '';
this._lookaheads = '';
this._overwrite = '';
},
/**
*
* important: _generate and _generateBody should never modify the term object.
*
* implementation notes:
*
* termRequiresWrap tells fragile term(s) in sub-expression that if protection is required.
* There are 2 situations:
* 0.no: If there is only one term, then the terms need not protection at all.
* 1.maybe: If the sub-expression is composed with more then one term,
* and the terms will be evaluated in order, i.e., will be concatenated directly,
* then the terms need not protection, unless it is the "either" expression.
*
* [in traditional chinese]
*
* termRequiresWrap 是要通知元素是否需要使用 group 來保護內容。
*
* 有兩種狀況:
*
* 0.no: 元素沒有兄弟元素(僅有一個子元素),則元素本身不需要特別保護。
* 1.maybe: 有兄弟元素,且兄弟元素之間將直接接合(concatenated),
* 元素應視需要(目前只有 either 運算式有此需要)自我保護。
*
* @protected
* @param {Object} context - the context object of the regexGen generator.
* @param {Number} termRequiresWrap - should the term requires wrap. See possible values descripted above.
* @returns {String} the generated regular expression string literal.
*/
_generate: function (context, termRequiresWrap) {
var i, n, body, bodyRequiresWrap;