natefw

natefw Commit Details


Date:2013-09-11 22:16:00 (11 years 3 months ago)
Author:Natalie Adams
Branch:default
Commit:ad86853a2662
Message:Migration from google code

Changes:
Alicense.txt (full)
Alinux/makefile (full)
Asrc/Matcher.cpp (full)
Asrc/Pattern.cpp (full)
Asrc/main.cpp (full)
Asrc/nfw.cpp (full)
Asrc/nfw.h (full)
Asrc/regexp/Matcher.h (full)
Asrc/regexp/Pattern.h (full)
Asrc/regexp/WCMatcher.h (full)
Asrc/regexp/WCPattern.h (full)
Awindows/nfw.bat (full)
Awindows/nfw.iss (full)

File differences

license.txt
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
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
linux/makefile
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
all: nfw
nfw: main.o nfw.o Matcher.o Pattern.o
g++ main.o nfw.o Matcher.o Pattern.o -o nfw
main.o: ../src/main.cpp
g++ -c ../src/main.cpp
nfw.o: ../src/nfw.cpp
g++ -c ../src/nfw.cpp
Matcher.o: ../src/Matcher.cpp
g++ -c ../src/Matcher.cpp
Pattern.o: ../src/Pattern.cpp
g++ -c ../src/Pattern.cpp
clean:
rm -rf *.o nfw
install: nfw
install -m 0755 nfw /usr/local/bin
uninstall: nfw
rm /usr/local/bin/nfw
src/Matcher.cpp
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
#include "regexp/Matcher.h"
#include "regexp/Pattern.h"
const int Matcher::MATCH_ENTIRE_STRING = 0x01;
/*
Detailed documentation is provided in this class' header file
@author Jeffery Stuart
@since November 2004
@version 1.07.00
*/
Matcher::Matcher(Pattern * pattern, const std::string & text)
{
pat = pattern;
str = text;
gc = pattern->groupCount;
ncgc = -pattern->nonCapGroupCount;
flags = 0;
matchedSomething = false;
starts = new int[gc + ncgc];
ends = new int[gc + ncgc];
groups = new int[gc + ncgc];
groupPos = new int[gc + ncgc];
groupIndeces = new int[gc + ncgc];
starts = starts + ncgc;
ends = ends + ncgc;
groups = groups + ncgc;
groupPos = groupPos + ncgc;
groupIndeces = groupIndeces + ncgc;
for (int i = 0; i < gc; ++i) starts[i] = ends[i] = 0;
}
Matcher::~Matcher()
{
delete [] (starts - ncgc);
delete [] (ends - ncgc);
delete [] (groups - ncgc);
delete [] (groupIndeces - ncgc);
delete [] (groupPos - ncgc);
}
void Matcher::clearGroups()
{
int i;
lm = 0;
for (i = 0; i < gc; ++i) groups[i] = starts[i] = ends[i] = -1;
for (i = 1; i <= ncgc; ++i) groups[0 - i] = -1;
}
std::string Matcher::replaceWithGroups(const std::string & str)
{
std::string ret = "";
std::string t = str;
while (t.size() > 0)
{
if (t[0] == '\\')
{
t = t.substr(1);
if (t.size() == 0)
{
ret += "\\";
}
else if (t[0] < '0' || t[0] > '9')
{
ret += t.substr(0, 1);
t = t.substr(1);
}
else
{
int gn = 0;
while (t.size() > 0 && t[0] >= '0' && t[0] <= '9')
{
gn = gn * 10 + (t[0] - '0');
t = t.substr(1);
}
ret += getGroup(gn);
}
}
else
{
ret += t.substr(0, 1);
t = t.substr(1);
}
}
return ret;
}
unsigned long Matcher::getFlags() const
{
return flags;
}
std::string Matcher::getText() const
{
return str;
}
bool Matcher::matches()
{
flags = MATCH_ENTIRE_STRING;
matchedSomething = false;
clearGroups();
lm = 0;
return pat->head->match(str, this, 0) == (int)str.size();
}
bool Matcher::findFirstMatch()
{
starts[0] = 0;
flags = 0;
clearGroups();
start = 0;
lm = 0;
ends[0] = pat->head->match(str, this, 0);
if (ends[0] >= 0)
{
matchedSomething = true;
return 1;
}
return 0;
}
bool Matcher::findNextMatch()
{
int s = starts[0], e = ends[0];
if (!matchedSomething) return findFirstMatch();
if (s == e) ++e;
flags = 0;
clearGroups();
starts[0] = e;
if (e >= (int)str.size()) return 0;
start = e;
lm = e;
ends[0] = pat->head->match(str, this, e);
return ends[0] >= 0;
}
std::vector<std::string> Matcher::findAll()
{
std::vector<std::string> ret;
reset();
while (findNextMatch())
{
ret.push_back(getGroup());
}
return ret;
}
void Matcher::reset()
{
lm = 0;
clearGroups();
matchedSomething = false;
}
int Matcher::getStartingIndex(const int groupNum) const
{
if (groupNum < 0 || groupNum >= gc) return -1;
return starts[groupNum];
}
int Matcher::getEndingIndex(const int groupNum) const
{
if (groupNum < 0 || groupNum >= gc) return -1;
return ends[groupNum];
}
std::string Matcher::getGroup(const int groupNum) const
{
if (groupNum < 0 || groupNum >= gc) return "";
if (starts[groupNum] < 0 || ends[groupNum] < 0) return "";
return str.substr(starts[groupNum], ends[groupNum] - starts[groupNum]);
}
std::vector<std::string> Matcher::getGroups(const bool includeGroupZero) const
{
int i, start = (includeGroupZero ? 0 : 1);
std::vector<std::string> ret;
for (i = start; i < gc; ++i) ret.push_back(getGroup(i));
return ret;
}
src/Pattern.cpp
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
/**
From the author (Jeff Stuart)
"
Let me start by saying this file is pretty big. If you feel up to it, you can
try making changes yourself, but you would be better off to just email me at
stuart@cs.ucdavis.edu if you think there is a bug, or have something useful you
would like added. This project is very "near and dear" to me, so I am fairly
quick to make bug fixes. The header files for Pattern and Matcher are fairly
well documented and the function names are pretty self-explanatory, but if you
are having any trouble, feel free to email me at stuart@cs.ucdavis.edu.
If you email me, make sure you put something like C++RE in the subject because
I tend to delete email if I don't recognize the name and the subject is
something like "I Need Your Help" or "Got A Second" or "I Found It".
"
*/
/*
Detailed documentation is provided in this class' header file
@author Jeffery Stuart
@since November 24th, 2007
@version 1.09.00
*/
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable:4996)
#define str_icmp stricmp
#else
#define str_icmp strcasecmp
#endif
#include "regexp/Pattern.h"
#include "regexp/Matcher.h"
#include <cstdio>
#include <cstring>
#include <typeinfo>
#include <algorithm>
std::map<std::string, Pattern *> Pattern::compiledPatterns;
std::map<std::string, std::pair<std::string, unsigned long> > Pattern::registeredPatterns;
const int Pattern::MIN_QMATCH = 0x00000000;
const int Pattern::MAX_QMATCH = 0x7FFFFFFF;
const unsigned long Pattern::CASE_INSENSITIVE = 0x01;
const unsigned long Pattern::LITERAL = 0x02;
const unsigned long Pattern::DOT_MATCHES_ALL = 0x04;
const unsigned long Pattern::MULTILINE_MATCHING = 0x08;
const unsigned long Pattern::UNIX_LINE_MODE = 0x10;
Pattern::Pattern(const std::string & rhs)
{
matcher = NULL;
pattern = rhs;
curInd = 0;
groupCount = 0;
nonCapGroupCount = 0;
error = 0;
head = NULL;
}
// convenience function in case we want to add any extra debugging output
void Pattern::raiseError()
{
switch (pattern[curInd - 1])
{
case '*':
case ')':
case '+':
case '?':
case ']':
case '}':
fprintf(stderr, "%s\n%*c^\n", pattern.c_str(), curInd - 1, ' ');
fprintf(stderr, "Syntax Error near here. Possible unescaped meta character.\n");
break;
default:
fprintf(stderr, "%s\n%*c^\n", pattern.c_str(), curInd - 1, ' ');
fprintf(stderr, "Syntax Error near here. \n");
break;
}
error = 1;
}
NFANode * Pattern::registerNode(NFANode * node)
{
nodes[node] = 1;
return node;
}
std::string Pattern::classUnion (std::string s1, std::string s2) const
{
char out[300];
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
*std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), out) = 0;
return out;
}
std::string Pattern::classIntersect (std::string s1, std::string s2) const
{
char out[300];
std::sort(s1.begin(), s1.end());
std::sort(s2.begin(), s2.end());
*std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), out) = 0;
return out;
}
std::string Pattern::classNegate (std::string s1) const
{
char out[300];
int i, ind = 0;
std::map<char, bool> m;
for (i = 0; i < (int)s1.size(); ++i)
{
m[s1[i]] = 1;
if (flags & CASE_INSENSITIVE)
{
if (s1[i] >= 'a' && s1[i] <= 'z') m[s1[i] - 'a' + 'A'] = 1;
else if (s1[i] >= 'A' && s1[i] <= 'Z') m[s1[i] - 'A' + 'a'] = 1;
}
}
for (i = 0xFF; i >= 0; --i) if (m.find((char)i) == m.end()) out[ind++] = (char)i;
out[ind] = 0;
return std::string(out, ind);
}
std::string Pattern::classCreateRange(char low, char hi) const
{
char out[300];
int ind = 0;
while (low != hi) out[ind++] = low++;
out[ind++] = low;
return std::string(out, ind);
}
int Pattern::getInt(int start, int end)
{
int ret = 0;
for (; start <= end; ++start) ret = ret * 10 + (pattern[start] - '0');
return ret;
}
bool Pattern::quantifyCurly(int & sNum, int & eNum)
{
bool good = 1;
int i, ci = curInd + 1;
int commaInd = ci, endInd = ci, len = pattern.size();
sNum = eNum = 0;
while (endInd < len && pattern[endInd ] != '}') ++endInd;
while (commaInd < endInd && pattern[commaInd] != ',') ++commaInd;
if (endInd >= len) { raiseError(); return 0; }
for (i = ci; good && i < endInd; ++i) if (i != commaInd && !isdigit(pattern[i])) good = 0;
if (!good && commaInd < endInd) { raiseError(); return 0; }
if (!good) return 0;
/* so now everything in here is either a comma (and there is at most one comma) or a digit */
if (commaInd == ci) // {,*}
{
if (endInd == commaInd + 1) { sNum = MIN_QMATCH; eNum = MAX_QMATCH; } // {,} = *
else { sNum = MIN_QMATCH; eNum = getInt(commaInd + 1, endInd - 1); } // {,+}
}
else if (commaInd == endInd - 1) { sNum = getInt(ci, commaInd - 1); eNum = MAX_QMATCH; } // {+,}
else if (commaInd == endInd) { sNum = getInt(ci, endInd - 1); eNum = sNum; } // {+}
else { sNum = getInt(ci, commaInd - 1); eNum = getInt(commaInd + 1, endInd - 1); } // {+,+}
curInd = endInd + 1;
return 1;
}
NFANode * Pattern::quantifyGroup(NFANode * start, NFANode * stop, const int gn)
{
NFANode * newNode = NULL;
int type = 0;
if (curInd < (int)pattern.size())
{
char ch = (curInd + 1 >= (int)pattern.size()) ? -1 : pattern[curInd + 1];
switch (pattern[curInd])
{
case '*':
++curInd;
switch (ch)
{
case '?': ++curInd; type = 1; break;
case '+': ++curInd; type = 2; break;
}
newNode = registerNode(new NFAGroupLoopPrologueNode(gn));
newNode->next = registerNode(new NFAGroupLoopNode(start, MIN_QMATCH, MAX_QMATCH, gn, type));
stop->next = newNode->next;
return newNode;
case '?':
++curInd;
switch (ch)
{
case '?': ++curInd; type = 1; break;
case '+': ++curInd; type = 2; break;
}
newNode = registerNode(new NFAGroupLoopPrologueNode(gn));
newNode->next = registerNode(new NFAGroupLoopNode(start, MIN_QMATCH, 1, gn, type));
stop->next = newNode->next;
return newNode;
case '+':
++curInd;
switch (ch)
{
case '?': ++curInd; type = 1; break;
case '+': ++curInd; type = 2; break;
}
newNode = registerNode(new NFAGroupLoopPrologueNode(gn));
newNode->next = registerNode(new NFAGroupLoopNode(start, 1, MAX_QMATCH, gn, type));
stop->next = newNode->next;
return newNode;
case '{':
{
int s, e;
if (quantifyCurly(s, e))
{
ch = (curInd < (int)pattern.size()) ? pattern[curInd] : -1;
switch (ch)
{
case '?': ++curInd; type = 1; break;
case '+': ++curInd; type = 2; break;
}
newNode = registerNode(new NFAGroupLoopPrologueNode(gn));
newNode->next = registerNode(new NFAGroupLoopNode(start, s, e, gn, type));
stop->next = newNode->next;
return newNode;
}
}
default:
break;
}
}
return NULL;
}
NFANode * Pattern::quantify(NFANode * newNode)
{
if (curInd < (int)pattern.size())
{
char ch = (curInd + 1 >= (int)pattern.size()) ? -1 : pattern[curInd + 1];
switch (pattern[curInd])
{
case '*':
++curInd;
switch (ch)
{
case '?': ++curInd; newNode = registerNode(new NFALazyQuantifierNode (this, newNode, MIN_QMATCH, MAX_QMATCH)); break;
case '+': ++curInd; newNode = registerNode(new NFAPossessiveQuantifierNode(this, newNode, MIN_QMATCH, MAX_QMATCH)); break;
default: newNode = registerNode(new NFAGreedyQuantifierNode (this, newNode, MIN_QMATCH, MAX_QMATCH)); break;
}
break;
case '?':
++curInd;
switch (ch)
{
case '?': ++curInd; newNode = registerNode(new NFALazyQuantifierNode (this, newNode, MIN_QMATCH, 1)); break;
case '+': ++curInd; newNode = registerNode(new NFAPossessiveQuantifierNode(this, newNode, MIN_QMATCH, 1)); break;
default: newNode = registerNode(new NFAGreedyQuantifierNode (this, newNode, MIN_QMATCH, 1)); break;
}
break;
case '+':
++curInd;
switch (ch)
{
case '?': ++curInd; newNode = registerNode(new NFALazyQuantifierNode (this, newNode, 1, MAX_QMATCH)); break;
case '+': ++curInd; newNode = registerNode(new NFAPossessiveQuantifierNode(this, newNode, 1, MAX_QMATCH)); break;
default: newNode = registerNode(new NFAGreedyQuantifierNode (this, newNode, 1, MAX_QMATCH)); break;
}
break;
case '{':
{
int s, e;
if (quantifyCurly(s, e))
{
ch = (curInd < (int)pattern.size()) ? pattern[curInd] : -1;
switch (ch)
{
case '?': ++curInd; newNode = registerNode(new NFALazyQuantifierNode (this, newNode, s, e)); break;
case '+': ++curInd; newNode = registerNode(new NFAPossessiveQuantifierNode(this, newNode, s, e)); break;
default: newNode = registerNode(new NFAGreedyQuantifierNode (this, newNode, s, e)); break;
}
}
}
break;
default:
break;
}
}
return newNode;
}
std::string Pattern::parseClass()
{
std::string t, ret = "";
char ch, c1, c2;
bool inv = 0, neg = 0, quo = 0;
if (curInd < (int)pattern.size() && pattern[curInd] == '^')
{
++curInd;
neg = 1;
}
while (curInd < (int)pattern.size() && pattern[curInd] != ']')
{
ch = pattern[curInd++];
if (ch == '[')
{
t = parseClass();
ret = classUnion(ret, t);
}
/*else if (ch == '-')
{
raiseError();
curInd = pattern.size();
}*/
else if (ch == '&' && curInd < (int)pattern.size() && pattern[curInd] == '&')
{
if (pattern[++curInd] != '[')
{
raiseError();
curInd = pattern.size();
}
else
{
++curInd;
t = parseClass();
ret = classIntersect(ret, t);
}
}
else if (ch == '\\')
{
t = parseEscape(inv, quo);
if (quo)
{
raiseError();
curInd = pattern.size();
}
else if (inv || t.size() > 1) // cant be part of a range (a-z)
{
if (inv) t = classNegate(t);
ret = classUnion(ret, t);
}
else if (curInd < (int)pattern.size() && pattern[curInd] == '-') // part of a range (a-z)
{
c1 = t[0];
++curInd;
if (curInd >= (int)pattern.size()) raiseError();
else
{
c2 = pattern[curInd++];
if (c2 == '\\')
{
t = parseEscape(inv, quo);
if (quo)
{
raiseError();
curInd = pattern.size();
}
else if (inv || t.size() > 1) raiseError();
else ret = classUnion(ret, classCreateRange(c1, c2));
}
else if (c2 == '[' || c2 == ']' || c2 == '-' || c2 == '&')
{
raiseError();
curInd = pattern.size();
}
else ret = classUnion(ret, classCreateRange(c1, c2));
}
}
else
{
ret = classUnion(ret, t);
}
}
else if (curInd < (int)pattern.size() && pattern[curInd] == '-')
{
c1 = ch;
++curInd;
if (curInd >= (int)pattern.size()) raiseError();
else
{
c2 = pattern[curInd++];
if (c2 == '\\')
{
t = parseEscape(inv, quo);
if (quo)
{
raiseError();
curInd = pattern.size();
}
else if (inv || t.size() > 1) raiseError();
else ret = classUnion(ret, classCreateRange(c1, c2));
}
else if (c2 == '[' || c2 == ']' || c2 == '-' || c2 == '&')
{
raiseError();
curInd = pattern.size();
}
else
{
ret = classUnion(ret, classCreateRange(c1, c2));
}
}
}
else
{
ret += " ";
ret[ret.size() - 1] = ch;
}
}
if (curInd >= (int)pattern.size() || pattern[curInd] != ']')
{
raiseError();
ret = "";
}
else
{
++curInd;
if (neg) ret = classNegate(ret);
}
return ret;
}
std::string Pattern::parsePosix()
{
std::string s7 = pattern.substr(curInd, 7);
if (s7 == "{Lower}") { curInd += 7; return "abcdefghijklmnopqrstuvwxyz"; }
if (s7 == "{Upper}") { curInd += 7; return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (s7 == "{Alpha}") { curInd += 7; return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (s7 == "{Digit}") { curInd += 7; return "0123456789"; }
if (s7 == "{Alnum}") { curInd += 7; return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; }
if (s7 == "{Punct}") { curInd += 7; return "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
if (s7 == "{Graph}") { curInd += 7; return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
if (s7 == "{Print}") { curInd += 7; return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
if (s7 == "{Blank}") { curInd += 7; return " \t"; }
if (s7 == "{Space}") { curInd += 7; return " \t\n\x0B\f\r"; }
if (s7 == "{Cntrl}")
{
int i;
std::string s = " ";
for (i = 0; i < 5; ++i) s += s;
s += " ";
for (i = 0; i <= 0x1F; ++i) s[i] = i;
s[0x20] = 0x7F;
curInd += 7;
return s;
}
if (s7 == "{ASCII}")
{
std::string s(0x80, ' ');
for (int i = 0; i < 0x80; ++i) s[i] = i;
curInd += 7;
return s;
}
if (pattern.substr(curInd, 8) == "{XDigit}") { curInd += 8; return "abcdefABCDEF0123456789"; }
raiseError();
return "";
}
NFANode * Pattern::parseBackref()
{
#define is_dig(x) ((x) >= '0' && (x) <= '9')
#define to_int(x) ((x) - '0')
int ci = curInd;
int oldRef = 0, ref = 0;
while (ci < (int)pattern.size() && is_dig(pattern[ci]) && (ref < 10 || ref < groupCount))
{
oldRef = ref;
ref = ref * 10 + to_int(pattern[ci++]);
}
if (ci == (int)pattern.size())
{
oldRef = ref;
++ci;
}
if (oldRef < 0 || ci <= curInd)
{
raiseError();
return registerNode(new NFAReferenceNode(-1));
}
curInd = ci;
return registerNode(new NFAReferenceNode(ref));
#undef is_dig
#undef to_int
}
std::string Pattern::parseOctal()
{
#define islowoc(x) ((x) >= '0' && (x) <= '3')
#define isoc(x) ((x) >= '0' && (x) <= '7')
#define fromoc(x) ((x) - '0')
int ci = curInd;
char ch1 = (ci + 0 < (int)pattern.size()) ? pattern[ci + 0] : -1;
char ch2 = (ci + 1 < (int)pattern.size()) ? pattern[ci + 1] : -1;
char ch3 = (ci + 2 < (int)pattern.size()) ? pattern[ci + 2] : -1;
std::string s = " ";
if (islowoc(ch1) && isoc(ch2))
{
curInd += 2;
s[0] = fromoc(ch1) * 8 + fromoc(ch2);
if (isoc(ch3))
{
++curInd;
s[0] = s[0] * 8 + fromoc(ch3);
}
}
else if (isoc(ch1) && isoc(ch2))
{
curInd += 2;
s[0] = fromoc(ch1) * 8 + fromoc(ch2);
}
else raiseError();
return s;
#undef islowoc
#undef isoc
#undef fromoc
}
std::string Pattern::parseHex()
{
#define to_low(x) (((x) >= 'A' && (x) <= 'Z') ? ((x) - 'A' + 'a') : (x))
#define is_dig(x) ((x) >= '0' && (x) <= '9')
#define is_hex(x) (is_dig(x) || (to_low(x) >= 'a' && to_low(x) <= 'f'))
#define to_int(x) ((is_dig(x)) ? ((x) - '0') : (to_low(x) - 'a' + 10))
int ci = curInd;
char ch1 = (ci + 0 < (int)pattern.size()) ? pattern[ci + 0] : -1;
char ch2 = (ci + 1 < (int)pattern.size()) ? pattern[ci + 1] : -1;
std::string s = " ";
if (is_hex(ch1) && is_hex(ch2))
{
curInd += 2;
s[0] = (to_int(ch1) << 4 & 0xF0) | (to_int(ch2) & 0x0F);
}
return s;
#undef to_low
#undef is_dig
#undef is_hex
#undef to_int
}
std::string Pattern::parseEscape(bool & inv, bool & quo)
{
char ch = pattern[curInd++];
std::string classes = "";
if (curInd > (int)pattern.size())
{
raiseError();
return NULL;
}
quo = 0;
inv = 0;
switch (ch)
{
case 'p': classes = parsePosix(); break;
case 'P': classes = "!!"; classes += parsePosix(); break;
case 'd': classes = "0123456789"; break;
case 'D': classes = "!!0123456789"; break;
case 's': classes = " \t\r\n\f"; break;
case 'S': classes = "!! \t\r\n\f"; break;
case 'w': classes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; break;
case 'W': classes = "!!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; break;
case '0': classes = parseOctal(); break;
case 'x': classes = parseHex(); break;
case 'Q': quo = 1; break;
case 't': classes = "\t"; break;
case 'r': classes = "\r"; break;
case 'n': classes = "\n"; break;
case 'f': classes = "\f"; break;
case 'a': classes = "\a"; break;
case 'e': classes = "\r"; break;
default: classes = " "; classes[0] = ch; break;
}
if (classes.substr(0, 2) == "!!")
{
classes = classes.substr(2);
inv = 1;
}
return classes;
}
NFANode * Pattern::parseRegisteredPattern(NFANode ** end)
{
int i, j;
std::string s;
NFANode * ret = NULL;
for (i = curInd; i < (int)pattern.size() && pattern[i] != '}'; ++i) { }
if (pattern[i] != '}') { raiseError(); return NULL; }
if (i == curInd + 1) { raiseError(); return NULL; } // {}
if (
!(
(pattern[curInd] >= 'a' && pattern[curInd] <= 'z') ||
(pattern[curInd] >= 'A' && pattern[curInd] <= 'Z') ||
(pattern[curInd] == '_')
)
)
{
raiseError();
return NULL;
}
for (j = curInd; !error && j < i; ++j)
{
if (
!(
(pattern[j] >= 'a' && pattern[j] <= 'z') ||
(pattern[j] >= 'A' && pattern[j] <= 'Z') ||
(pattern[j] >= '0' && pattern[j] <= '9') ||
(pattern[j] == '_')
)
)
{
raiseError();
return NULL;
}
}
s = pattern.substr(curInd, i - curInd);
if (registeredPatterns.find(s) == registeredPatterns.end()) raiseError();
else
{
unsigned long oflags = flags;
std::string op = pattern;
int ci = i + 1;
pattern = registeredPatterns[s].first;
curInd = 0;
flags = registeredPatterns[s].second;
--groupCount;
ret = parse(0, 0, end);
pattern = op;
curInd = ci;
flags = oflags;
}
if (error) { *end = ret = NULL; }
return ret;
}
// look behind should interpret everything as a literal (except \\) since the
// pattern must have a concrete length
NFANode * Pattern::parseBehind(const bool pos, NFANode ** end)
{
std::string t = "";
while (curInd < (int)pattern.size() && pattern[curInd] != ')')
{
char ch = pattern[curInd++];
t += " ";
if (ch == '\\')
{
if (curInd + 1 >= (int)pattern.size())
{
raiseError();
return *end = registerNode(new NFACharNode(' '));
}
ch = pattern[curInd++];
}
t[t.size() - 1] = ch;
}
if (curInd >= (int)pattern.size() || pattern[curInd] != ')') raiseError();
else ++curInd;
return *end = registerNode(new NFALookBehindNode(t, pos));
}
NFANode * Pattern::parseQuote()
{
bool done = 0;
std::string s = "";
while (!done)
{
if (curInd >= (int)pattern.size())
{
raiseError();
done = 1;
}
else if (pattern.substr(curInd, 2) == "\\E")
{
curInd += 2;
done = 1;
}
else if (pattern[curInd] == '\\')
{
s += " ";
s[s.size() - 1] = pattern[++curInd];
++curInd;
}
else
{
s += " ";
s[s.size() - 1] = pattern[curInd++];
}
}
if ((flags & Pattern::CASE_INSENSITIVE) != 0) return registerNode(new NFACIQuoteNode(s));
return registerNode(new NFAQuoteNode(s));
}
NFANode * Pattern::parse(const bool inParen, const bool inOr, NFANode ** end, const int orGroup, const bool inOrCap)
{
NFANode * start, * cur, * next = NULL;
std::string t;
int grc = groupCount++;
bool inv, quo;
bool ahead = false, pos = false, noncap = false, indep = false;
unsigned long oldFlags = flags;
if (inParen)
{
if (inOr)
{
--groupCount;
noncap = !inOrCap;
grc = orGroup;
if (noncap) cur = start = registerNode(new NFAGroupHeadNode(grc));
else cur = start = registerNode(new NFASubStartNode);
}
else if (pattern[curInd] == '?')
{
++curInd;
--groupCount;
if (pattern[curInd] == ':') { noncap = 1; ++curInd; grc = --nonCapGroupCount; }
else if (pattern[curInd] == '=') { ++curInd; ahead = 1; pos = 1; }
else if (pattern[curInd] == '!') { ++curInd; ahead = 1; pos = 0; }
else if (pattern.substr(curInd, 2) == "<=") { curInd += 2; return parseBehind(1, end); }
else if (pattern.substr(curInd, 2) == "<!") { curInd += 2; return parseBehind(0, end); }
else if (pattern[curInd] == '>') { ++curInd; indep = 1; }
else
{
bool negate = false, done = false;
while (!done)
{
if (curInd >= (int)pattern.size())
{
raiseError();
return NULL;
}
else if (negate)
{
switch (pattern[curInd])
{
case 'i': flags &= ~Pattern::CASE_INSENSITIVE; break;
case 'd': flags &= ~Pattern::UNIX_LINE_MODE; break;
case 'm': flags &= ~Pattern::MULTILINE_MATCHING; break;
case 's': flags &= ~Pattern::DOT_MATCHES_ALL; break;
case ':': done = true; break;
case ')':
++curInd;
*end = registerNode(new NFALookBehindNode("", true));
return *end;
case '-':
default: raiseError(); return NULL;
}
}
else
{
switch (pattern[curInd])
{
case 'i': flags |= Pattern::CASE_INSENSITIVE; break;
case 'd': flags |= Pattern::UNIX_LINE_MODE; break;
case 'm': flags |= Pattern::MULTILINE_MATCHING; break;
case 's': flags |= Pattern::DOT_MATCHES_ALL; break;
case ':': done = true; break;
case '-': negate = true; break;
case ')':
++curInd;
*end = registerNode(new NFALookBehindNode("", true));
return *end;
default: raiseError(); return NULL;
}
}
++curInd;
}
noncap = 1;
grc = --nonCapGroupCount;
}
if (noncap) cur = start = registerNode(new NFAGroupHeadNode(grc));
else cur = start = registerNode(new NFASubStartNode);
}
else cur = start = registerNode(new NFAGroupHeadNode(grc));
}
else cur = start = registerNode(new NFASubStartNode);
while (curInd < (int)pattern.size())
{
char ch = pattern[curInd++];
next = NULL;
if (error) return NULL;
switch (ch)
{
case '^':
if ((flags & Pattern::MULTILINE_MATCHING) != 0) next = registerNode(new NFAStartOfLineNode);
else next = registerNode(new NFAStartOfInputNode);
break;
case '$':
if ((flags & Pattern::MULTILINE_MATCHING) != 0) next = registerNode(new NFAEndOfLineNode);
else next = registerNode(new NFAEndOfInputNode(0));
break;
case '|':
cur->next = registerNode(new NFAAcceptNode);
cur = start = registerNode(new NFAOrNode(start, parse(inParen, true, NULL, grc, !noncap)));
break;
case '\\':
if (curInd < (int)pattern.size())
{
bool eoi = 0;
switch (pattern[curInd])
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': next = parseBackref(); break;
case 'A': ++curInd; next = registerNode(new NFAStartOfInputNode); break;
case 'B': ++curInd; next = registerNode(new NFAWordBoundaryNode(0)); break;
case 'b': ++curInd; next = registerNode(new NFAWordBoundaryNode(1)); break;
case 'G': ++curInd; next = registerNode(new NFAEndOfMatchNode); break;
case 'Z': eoi = 1;
case 'z': ++curInd; next = registerNode(new NFAEndOfInputNode(eoi)); break;
default:
t = parseEscape(inv, quo);
if (!quo)
{
if (t.size() > 1 || inv)
{
if ((flags & Pattern::CASE_INSENSITIVE) != 0) next = registerNode(new NFACIClassNode(t, inv));
else next = registerNode(new NFAClassNode(t, inv));
}
else
{
next = registerNode(new NFACharNode(t[0]));
}
}
else
{
next = parseQuote();
}
}
}
else raiseError();
break;
case '[':
if ((flags & Pattern::CASE_INSENSITIVE) == 0)
{
NFAClassNode * clazz = new NFAClassNode();
std::string s = parseClass();
for (int i = 0; i < (int)s.size(); ++i) clazz->vals[s[i]] = 1;
next = registerNode(clazz);
}
else
{
NFACIClassNode * clazz = new NFACIClassNode();
std::string s = parseClass();
for (int i = 0; i < (int)s.size(); ++i) clazz->vals[tolower(s[i])] = 1;
next = registerNode(clazz);
}
break;
case '.':
{
bool useN = 1, useR = 1;
NFAClassNode * clazz = new NFAClassNode(1);
if ((flags & Pattern::UNIX_LINE_MODE) != 0) useR = 0;
if ((flags & Pattern::DOT_MATCHES_ALL) != 0) useN = useR = 0;
if (useN) clazz->vals['\n'] = 1;
if (useR) clazz->vals['\r'] = 1;
next = registerNode(clazz);
}
break;
case '(':
{
NFANode * end, * t1, * t2;
t1 = parse(true, false, &end);
if (!t1) raiseError();
else if (t1->isGroupHeadNode() && (t2 = quantifyGroup(t1, end, grc)) != NULL)
{
cur->next = t2;
cur = t2->next;
}
else
{
cur->next = t1;
cur = end;
}
}
break;
case ')':
if (!inParen) raiseError();
else if (inOr)
{
--curInd;
cur = cur->next = registerNode(new NFAAcceptNode);
flags = oldFlags;
return start;
}
else
{
if (ahead)
{
cur = cur->next = registerNode(new NFAAcceptNode);
flags = oldFlags;
return *end = registerNode(new NFALookAheadNode(start, pos));
}
else if (indep)
{
cur = cur->next = registerNode(new NFAAcceptNode);
flags = oldFlags;
return *end = registerNode(new NFAPossessiveQuantifierNode(this, start, 1, 1));
}
else // capping or noncapping, it doesnt matter
{
*end = cur = cur->next = registerNode(new NFAGroupTailNode(grc));
next = quantifyGroup(start, *end, grc);
if (next)
{
start = next;
*end = next->next;
}
flags = oldFlags;
return start;
}
}
break;
case '{': // registered pattern
cur->next = parseRegisteredPattern(&next);
if (cur->next) cur = next;
break;
case '*':
case '+':
case '?':
case '}':
case ']':
raiseError();
break;
default:
if ((flags & Pattern::CASE_INSENSITIVE) != 0) next = registerNode(new NFACICharNode(ch));
else next = registerNode(new NFACharNode(ch));
break;
}
NFAOrNode * orNode = dynamic_cast<NFAOrNode *>(cur);
if (orNode) // an orNode will never have a "next" set. thus we don't have to worry about problems with
{ // quantifying an or node.
NFANode * one = orNode->one, * two = orNode->two;
while (one->next) one = one->next;
while (two->next) two = two->next;
one->next = two->next = cur = registerNode(new NFAAcceptNode);
}
if (next)
{
cur = cur->next = quantify(next);
}
}
if (inParen) raiseError();
else
{
if (inOr) cur = cur->next = registerNode(new NFAAcceptNode);
if (end) *end = cur;
}
flags = oldFlags;
if (error) return NULL;
return start;
}
Pattern * Pattern::compile(const std::string & pattern, const unsigned long mode)
{
Pattern * p = new Pattern(pattern);
NFANode * end;
p->flags = mode;
if ((mode & Pattern::LITERAL) != 0)
{
p->head = p->registerNode(new NFAStartNode);
if ((mode & Pattern::CASE_INSENSITIVE) != 0) p->head->next = p->registerNode(new NFACIQuoteNode(pattern));
else p->head->next = p->registerNode(new NFAQuoteNode(pattern));
p->head->next->next = p->registerNode(new NFAEndNode);
}
else
{
p->head = p->parse(0, 0, &end);
if (!p->head)
{
delete p;
p = NULL;
}
else
{
if (!(p->head && p->head->isStartOfInputNode()))
{
NFANode * n = p->registerNode(new NFAStartNode);
n->next = p->head;
p->head = n;
}
end->next = p->registerNode(new NFAEndNode);
}
}
if (p != NULL)
{
p->matcher = new Matcher(p, "");
}
return p;
}
Pattern * Pattern::compileAndKeep(const std::string & pattern, const unsigned long mode)
{
Pattern * ret = NULL;
std::map<std::string, Pattern*>::iterator it = compiledPatterns.find(pattern);
if (it != compiledPatterns.end())
{
ret = it->second;
}
else
{
ret = compile(pattern, mode);
compiledPatterns[pattern] = ret;
}
return ret;
}
std::string Pattern::replace(const std::string & pattern, const std::string & str,
const std::string & replacementText, const unsigned long mode)
{
std::string ret;
Pattern * p = Pattern::compile(pattern, mode);
if (p)
{
ret = p->replace(str, replacementText);
delete p;
}
return ret;
}
std::vector<std::string> Pattern::split(const std::string & pattern, const std::string & str, const bool keepEmptys,
const unsigned long limit, const unsigned long mode)
{
std::vector<std::string> ret;
Pattern * p = Pattern::compile(pattern, mode);
if (p)
{
ret = p->split(str, keepEmptys, limit);
delete p;
}
return ret;
}
std::vector<std::string> Pattern::findAll(const std::string & pattern, const std::string & str, const unsigned long mode)
{
std::vector<std::string> ret;
Pattern * p = Pattern::compile(pattern, mode);
if (p)
{
ret = p->findAll(str);
delete p;
}
return ret;
}
bool Pattern::matches(const std::string & pattern, const std::string & str, const unsigned long mode)
{
bool ret = 0;
Pattern * p = compile(pattern, mode);
if (p)
{
ret = p->matches(str);
delete p;
}
return ret;
}
bool Pattern::registerPattern(const std::string & name, const std::string & pattern, const unsigned long mode)
{
Pattern * p = Pattern::compile(pattern, mode);
if (!p) return 0;
Pattern::registeredPatterns[name] = std::make_pair(pattern, mode);
delete p;
return 1;
}
void Pattern::unregisterPatterns()
{
registeredPatterns.clear();
}
void Pattern::clearPatternCache()
{
std::map<std::string, Pattern*>::iterator it;
for (it = compiledPatterns.begin(); it != compiledPatterns.end(); ++it)
{
delete it->second;
}
compiledPatterns.clear();
}
std::pair<std::string, int> Pattern::findNthMatch(const std::string & pattern, const std::string & str,
const int matchNum, const unsigned long mode)
{
std::pair<std::string, int> ret;
Pattern * p = Pattern::compile(pattern, mode);
ret.second = -1;
if (p)
{
int i = -1;
p->matcher->setString(str);
while (i < matchNum && p->matcher->findNextMatch()) { ++i; }
if (i == matchNum && p->matcher->getStartingIndex() >= 0)
{
ret.first = p->matcher->getGroup(0);
ret.second = p->matcher->getStartingIndex();
}
delete p;
}
return ret;
}
Pattern::~Pattern()
{
if (matcher) delete matcher;
for (std::map<NFANode*, bool>::iterator it = nodes.begin(); it != nodes.end(); ++it)
{
delete it->first;
}
}
std::string Pattern::replace(const std::string & str, const std::string & replacementText)
{
int li = 0;
std::string ret = "";
matcher->setString(str);
while (matcher->findNextMatch())
{
ret += str.substr(li, matcher->getStartingIndex() - li);
ret += matcher->replaceWithGroups(replacementText);
li = matcher->getEndingIndex();
}
ret += str.substr(li);
return ret;
}
std::vector<std::string> Pattern::split(const std::string & str, const bool keepEmptys, const unsigned long limit)
{
unsigned long lim = (limit == 0 ? MAX_QMATCH : limit);
int li = 0;
std::vector<std::string> ret;
matcher->setString(str);
while (matcher->findNextMatch() && ret.size() < lim)
{
if (matcher->getStartingIndex() == 0 && keepEmptys) ret.push_back("");
if ((matcher->getStartingIndex() != matcher->getEndingIndex()) || keepEmptys)
{
if (li != matcher->getStartingIndex() || keepEmptys)
{
ret.push_back(str.substr(li, matcher->getStartingIndex() - li));
}
li = matcher->getEndingIndex();
}
}
if (li < (int)str.size()) ret.push_back(str.substr(li));
return ret;
}
std::vector<std::string> Pattern::findAll(const std::string & str)
{
matcher->setString(str);
return matcher->findAll();
}
bool Pattern::matches(const std::string & str)
{
matcher->setString(str);
return matcher->matches();
}
unsigned long Pattern::getFlags() const
{
return flags;
}
std::string Pattern::getPattern() const
{
return pattern;
}
Matcher * Pattern::createMatcher(const std::string & str)
{
return new Matcher(this, str);
}
void Pattern::print()
{
printf("Pattern(%s):\n", pattern.c_str());
if (head) head->print(1);
}
static char * getPrintChar(const char ch)
{
static char buf[1024];
if (ch == '0') strcpy(buf, "\\0");
else if (ch == '\r') strcpy(buf, "\\r");
else if (ch == '\t') strcpy(buf, "\\t");
else if (ch == '\n') strcpy(buf, "\\n");
else if (ch == 0x0C) strcpy(buf, "\\p");
else if (ch < ' ' || ch >= 0x80) sprintf(buf, "0x%02X", ch);
else sprintf(buf, "%c", ch);
return buf;
}
static void appendRawToClass(const int ch, char * const buf, int & curInd)
{
switch (ch)
{
case '(':
case ')':
case '\\':
case '-':
case '[':
case ']':
buf[curInd++] = '\\';
default:;
buf[curInd++] = (char)ch;
}
}
static void appendToClass0(const int j, int & start, const bool raw, const bool allowRanges, char * const buf, int & curInd)
{
if (start != -1)
{
if (start + 1 == j)
{
if (raw)
{
appendRawToClass(start, buf, curInd);
}
else
{
sprintf(buf + curInd, "\\x%02X", start);
curInd += 4;
}
}
else if (start + 2 == j)
{
if (raw)
{
appendRawToClass(start, buf, curInd);
appendRawToClass(start + 1, buf, curInd);
}
else
{
sprintf(buf + curInd, "\\x%02X\\x%02X", start, start + 1);
curInd += 8;
}
}
else
{
if (allowRanges)
{
if (raw)
{
appendRawToClass(start, buf, curInd);
buf[curInd++] = '-';
appendRawToClass(j - 1, buf, curInd);
}
else
{
sprintf(buf + curInd, "\\x%02X-\\x%02X", start, j - 1);
curInd += 9;
}
}
else
{
for (int k = start; k < j; ++k)
{
appendRawToClass(k, buf, curInd);
}
}
}
}
start = -1;
}
static void appendToClass(const std::map<char, bool> & chars, const int * const range, const bool raw, const bool allowRanges, char * const buf, int & curInd)
{
int start = -1, j;
for (j = range[0]; j < range[1]; ++j)
{
if (chars.find((char)j) != chars.end())
{
if (start == -1) start = j;
}
else
{
appendToClass0(j, start, raw, allowRanges, buf, curInd);
}
}
appendToClass0(j, start, raw, allowRanges, buf, curInd);
}
static char * getClassDesc(const std::map<char, bool> & chars, const bool inv, const bool firstPass = true)
{
static char buf[1024];
int curInd = 0;
bool ok[256] = { false };
buf[curInd++] = '[';
if (inv)
{
buf[curInd++] = '^';
}
// check for lower case letters
if (chars.find(' ') != chars.end()) { buf[curInd++] = ' '; }
if (chars.find(0x00) != chars.end()) { strcpy(buf + curInd, "\\0"); curInd += 2; }
if (chars.find('\t') != chars.end()) { strcpy(buf + curInd, "\\t"); curInd += 2; }
if (chars.find('\r') != chars.end()) { strcpy(buf + curInd, "\\r"); curInd += 2; }
if (chars.find('\n') != chars.end()) { strcpy(buf + curInd, "\\n"); curInd += 2; }
if (chars.find(0x0c) != chars.end()) { strcpy(buf + curInd, "\\p"); curInd += 2; }
const int HEX_RANGES[][2] =
{
{ 0x01, 0x09 },
{ 0x0B, 0x0B },
{ 0x0E, 0x20 },
{ 0x80, 0x100 },
};
const int RAW_RANGES[][2] =
{
{ 0x20, '0' },
{ '0', '9' + 1 },
{ '9' + 1, 'A' },
{ 'A', 'Z' + 1 },
{ 'Z' + 1, 'a' },
{ 'a', 'z' + 1 },
{ 'z' + 1, 0x80 },
};
const bool ALLOW_RANGES[] =
{
false,
true,
false,
true,
false,
true,
false,
};
const int NUM_HEX = sizeof(HEX_RANGES) / sizeof(HEX_RANGES[0]);
const int NUM_RAW = sizeof(RAW_RANGES) / sizeof(RAW_RANGES[0]);
for (int i = 0; i < NUM_HEX; ++i)
{
appendToClass(chars, HEX_RANGES[i], false, true, buf, curInd);
}
for (int i = 0; i < NUM_RAW; ++i)
{
appendToClass(chars, RAW_RANGES[i], true, ALLOW_RANGES[i], buf, curInd);
}
buf[curInd++] = ']';
buf[curInd++] = 0;
if (firstPass)
{
char newBuf[1024];
std::map<char, bool> invChars;
for (int i = 0; i < 256; ++i)
{
if (chars.find((char)i) == chars.end()) invChars[(char)i] = true;
}
strcpy(newBuf, buf);
getClassDesc(invChars, !inv, false);
if (strlen(buf) > strlen(newBuf)) strcpy(buf, newBuf);
}
return buf;
}
// NFANode
NFANode::NFANode() { next = NULL; }
NFANode::~NFANode() { }
void NFANode::findAllNodes(std::map<NFANode*, bool> & soFar)
{
if (soFar.find(this) == soFar.end()) return;
soFar[this] = 1;
if (next) next->findAllNodes(soFar);
}
void NFANode::print(const int indent)
{
printf("%*c%s\n", indent * 2, ' ', typeid(*this).name());
if (next) next->print(indent);
}
// NFACharNode
NFACharNode::NFACharNode(const char c) { ch = c; }
int NFACharNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd < (int)str.size() && str[curInd] == ch) return next->match(str, matcher, curInd + 1, depth + 1);
return -1;
}
void NFACharNode::print(const int indent)
{
printf("%*c%s(0x%02X)\n", indent * 2, ' ', typeid(*this).name(), ch);
if (next) next->print(indent);
}
// NFACICharNode
NFACICharNode::NFACICharNode(const char c) { ch = tolower(c); }
int NFACICharNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd < (int)str.size() && tolower(str[curInd]) == ch) return next->match(str, matcher, curInd + 1, depth + 1);
return -1;
}
void NFACICharNode::print(const int indent)
{
printf("%*c%s(0x%02X)\n", indent * 2, ' ', typeid(*this).name(), ch);
if (next) next->print(indent);
}
// NFAStartNode
NFAStartNode::NFAStartNode() { }
int NFAStartNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ret = -1, ci = curInd;
matcher->starts[0] = curInd;
if ((matcher->getFlags() & Matcher::MATCH_ENTIRE_STRING) == (unsigned int)Matcher::MATCH_ENTIRE_STRING)
{
if (curInd != 0)
{
matcher->starts[0] = -1;
return -1;
}
return next->match(str, matcher, 0, depth + 1);
}
while ((ret = next->match(str, matcher, ci)) == -1 && ci < (int)str.size())
{
matcher->clearGroups();
matcher->starts[0] = ++ci;
}
if (ret < 0) matcher->starts[0] = -1;
return ret;
}
// NFAEndNode
NFAEndNode::NFAEndNode() { }
int NFAEndNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
matcher->ends[0] = curInd;
if ((matcher->getFlags() & Matcher::MATCH_ENTIRE_STRING) != 0)
{
if (curInd == (int)str.size()) return curInd;
matcher->ends[0] = -1;
return -1;
}
return curInd;
}
// NFAQuantifierNode
void NFAQuantifierNode::findAllNodes(std::map<NFANode*, bool> & soFar)
{
inner->findAllNodes(soFar);
NFANode::findAllNodes(soFar);
}
NFAQuantifierNode::NFAQuantifierNode(Pattern * pat, NFANode * internal, const int minMatch, const int maxMatch)
{
inner = internal;
inner->next = pat->registerNode(new NFAAcceptNode);
min = (minMatch < Pattern::MIN_QMATCH) ? Pattern::MIN_QMATCH : minMatch;
max = (maxMatch > Pattern::MAX_QMATCH) ? Pattern::MAX_QMATCH : maxMatch;
}
int NFAQuantifierNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int i0, i1, i2 = 0;
i0 = i1 = curInd;
while (i2 < min)
{
++i2;
i1 = inner->match(str, matcher, i0, depth + 1);
if (i1 <= i0) return i1; // i1 < i0 means i1 is -1
i0 = i1;
}
return i1;
}
void NFAQuantifierNode::print(const int indent)
{
printf("%*c%s(min=%d, max=%d)\n", indent * 2, ' ', typeid(*this).name(), min, max);
printf("%*cinner\n", (indent + 1) * 2, ' ');
if (inner) inner->print(indent + 2);
if (next) next->print(indent);
}
// NFAGreedyQuantifierNode
NFAGreedyQuantifierNode::NFAGreedyQuantifierNode(Pattern * pat, NFANode * internal, const int minMatch, const int maxMatch)
: NFAQuantifierNode(pat, internal, minMatch, maxMatch) { }
int NFAGreedyQuantifierNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int t = NFAQuantifierNode::match(str, matcher, curInd, depth + 1);
if (t != -1) return matchInternal(str, matcher, t, min, depth + 1);
return t;
}
int NFAGreedyQuantifierNode::matchInternal(const std::string & str, Matcher * matcher, const int curInd, const int soFar, const int depth) const
{
if (soFar >= max) return next->match(str, matcher, curInd, depth + 1);
int i, j;
i = inner->match(str, matcher, curInd, depth + 1);
if (i != -1)
{
j = matchInternal(str, matcher, i, soFar + 1, depth + 1);
if (j != -1) return j;
}
return next->match(str, matcher, curInd, depth + 1);
}
// NFALazyQuantifierNode
NFALazyQuantifierNode::NFALazyQuantifierNode(Pattern * pat, NFANode * internal, const int minMatch, const int maxMatch)
: NFAQuantifierNode(pat, internal, minMatch, maxMatch) { }
int NFALazyQuantifierNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int i, j, m = NFAQuantifierNode::match(str, matcher, curInd, depth + 1);
if (m == -1) return -1;
for (i = min; i < max; ++i)
{
j = next->match(str, matcher, m, depth + 1);
if (j == -1)
{
j = inner->match(str, matcher, m, depth + 1);
// if j < m, then j is -1, so we bail.
// if j == m, then we would just go and call next->match on the same index,
// but it already failed trying to match right there, so we know we can
// just bail
if (j <= m) return -1;
m = j;
}
else return j;
}
return next->match(str, matcher, m, depth + 1);
}
// NFAPossessiveQuantifierNode
NFAPossessiveQuantifierNode::NFAPossessiveQuantifierNode(Pattern * pat, NFANode * internal, const int minMatch, const int maxMatch)
: NFAQuantifierNode(pat, internal, minMatch, maxMatch) { }
int NFAPossessiveQuantifierNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int i, j, m = NFAQuantifierNode::match(str, matcher, curInd, depth + 1);
if (m == -1) return -1;
for (i = min; i < max; ++i)
{
j = inner->match(str, matcher, m, depth + 1);
if (j <= m) return next->match(str, matcher, m, depth + 1);
m = j;
}
return next->match(str, matcher, m, depth + 1);
}
// NFAAcceptNode
NFAAcceptNode::NFAAcceptNode() { }
int NFAAcceptNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (!next) return curInd;
else return next->match(str, matcher, curInd, depth + 1);
}
// NFAClassNode
NFAClassNode::NFAClassNode(const bool invert)
{
inv = invert;
}
NFAClassNode::NFAClassNode(const std::string & clazz, const bool invert)
{
inv = invert;
for (int i = 0; i < (int)clazz.size(); ++i) vals[clazz[i]] = 1;
}
int NFAClassNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd < (int)str.size() && ((vals.find(str[curInd]) != vals.end()) ^ inv))
{
return next->match(str, matcher, curInd + 1, depth + 1);
}
return -1;
}
void NFAClassNode::print(const int indent)
{
printf("%*c%s(%d vals, inv=%s)\n", indent * 2, ' ', typeid(*this).name(), (int)vals.size(), inv ? "true" : "false");
if (next) next->print(indent);
}
// NFACIClassNode
NFACIClassNode::NFACIClassNode(const bool invert)
{
inv = invert;
}
NFACIClassNode::NFACIClassNode(const std::string & clazz, const bool invert)
{
inv = invert;
for (int i = 0; i < (int)clazz.size(); ++i) vals[tolower(clazz[i])] = 1;
}
int NFACIClassNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd < (int)str.size() && ((vals.find(tolower(str[curInd])) != vals.end()) ^ inv))
{
return next->match(str, matcher, curInd + 1, depth + 1);
}
return -1;
}
void NFACIClassNode::print(const int indent)
{
if (next) next->print(indent);
}
#undef to_lower
// NFASubStartNode
NFASubStartNode::NFASubStartNode() { }
int NFASubStartNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
return next->match(str, matcher, curInd, depth + 1);
}
// NFAOrNode
NFAOrNode::NFAOrNode(NFANode * first, NFANode * second) : one(first), two(second) { }
void NFAOrNode::findAllNodes(std::map<NFANode*, bool> & soFar)
{
if (one) one->findAllNodes(soFar);
if (two) two->findAllNodes(soFar);
NFANode::findAllNodes(soFar);
}
int NFAOrNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ci = one->match(str, matcher, curInd, depth + 1);
if (ci != -1) return ci;
return two->match(str, matcher, curInd, depth + 1);
/*
int ci = one->match(str, matcher, curInd, depth + 1);
if (ci != -1)
{
ci = next->match(str, matcher, ci, depth + 1);
if (ci != -1) return ci;
}
ci = two->match(str, matcher, curInd, depth + 1);
if (ci != -1) ci = next->match(str, matcher, ci, depth + 1);
return -1;
*/
}
void NFAOrNode::print(const int indent)
{
printf("%*c%s\n", indent * 2, ' ', typeid(*this).name());
printf("%*cone\n", (indent + 1) * 2, ' ');
one->print(indent + 2);
printf("%*ctwo\n", (indent + 1) * 2, ' ');
two->print(indent + 2);
}
// NFAQuoteNode
NFAQuoteNode::NFAQuoteNode(const std::string & quoted) : qStr(quoted) { }
int NFAQuoteNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd + qStr.size() > str.size()) return -1;
if (str.substr(curInd, qStr.size()) != qStr) return -1;
return next->match(str, matcher, curInd + qStr.size(), depth + 1);
}
void NFAQuoteNode::print(const int indent)
{
printf("%*c%s(%s)\n", indent * 2, ' ', typeid(*this).name(), qStr.c_str());
if (next) next->print(indent);
}
// NFACIQuoteNode
NFACIQuoteNode::NFACIQuoteNode(const std::string & quoted) : qStr(quoted) { }
int NFACIQuoteNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd + qStr.size() > str.size()) return -1;
if (str_icmp(str.substr(curInd, qStr.size()).c_str(), qStr.c_str())) return -1;
return next->match(str, matcher, qStr.size(), depth + 1);
}
void NFACIQuoteNode::print(const int indent)
{
printf("%*c%s(%s)\n", indent * 2, ' ', typeid(*this).name(), qStr.c_str());
if (next) next->print(indent);
}
// NFALookAheadNode
NFALookAheadNode::NFALookAheadNode(NFANode * internal, const bool positive) : NFANode(), pos(positive), inner(internal) { }
void NFALookAheadNode::findAllNodes(std::map<NFANode*, bool> & soFar)
{
if (inner) inner->findAllNodes(soFar);
NFANode::findAllNodes(soFar);
}
int NFALookAheadNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
return ((inner->match(str, matcher, curInd, depth + 1) == -1) ^ pos) ? next->match(str, matcher, curInd, depth + 1) : -1;
}
void NFALookAheadNode::print(const int indent)
{
printf("%*c%s(pos=%s)\n", indent * 2, ' ', typeid(*this).name(), pos ? "true" : "false");
inner->print(indent + 1);
if (next) next->print(indent);
}
// NFALookBehindNode
NFALookBehindNode::NFALookBehindNode(const std::string & str, const bool positive) : pos(positive), mStr(str) { }
int NFALookBehindNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (pos)
{
if (curInd < (int)mStr.size()) return -1;
if (str.substr(curInd - mStr.size(), mStr.size()) == mStr) return next->match(str, matcher, curInd, depth + 1);
}
else
{
if (curInd < (int)mStr.size()) return next->match(str, matcher, curInd, depth + 1);
if (str.substr(curInd - mStr.size(), mStr.size()) == mStr) return -1;
return next->match(str, matcher, curInd, depth + 1);
}
return -1;
}
void NFALookBehindNode::print(const int indent)
{
printf("%*c%s(str=%s, pos=%s)\n", indent * 2, ' ', typeid(*this).name(), mStr.c_str(), pos ? "true" : "false");
if (next) next->print(indent);
}
// NFAStartOfLineNode
NFAStartOfLineNode::NFAStartOfLineNode() { }
int NFAStartOfLineNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd == 0 || str[curInd - 1] == '\n' || str[curInd - 1] == '\r')
{
return next->match(str, matcher, curInd, depth + 1);
}
return -1;
}
// NFAEndOfLineNode
NFAEndOfLineNode::NFAEndOfLineNode() { }
int NFAEndOfLineNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd >= (int)str.size() || str[curInd] == '\n' || str[curInd] == '\r')
{
return next->match(str, matcher, curInd, depth + 1);
}
return -1;
}
// NFAReferenceNode
NFAReferenceNode::NFAReferenceNode(const int groupIndex) : gi(groupIndex) { }
int NFAReferenceNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int len = matcher->ends[gi] - matcher->starts[gi];
int ni = -1;
if (gi < 1 || matcher->ends[gi] < matcher->starts[gi] || len == 0) ni = curInd;
else if (curInd + len > (int)str.size()) return -1;
else if (str.substr(curInd, len) != str.substr(matcher->starts[gi], len)) return -1;
else ni = curInd + len;
return next->match(str, matcher, ni, depth + 1);
}
void NFAReferenceNode::print(const int indent)
{
printf("%*c%s(gi=%d)\n", indent * 2, ' ', typeid(*this).name(), gi);
if (next) next->print(indent);
}
// NFAStartOfInputNode
NFAStartOfInputNode::NFAStartOfInputNode() { }
int NFAStartOfInputNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd == 0) return next->match(str, matcher, curInd, depth + 1);
return -1;
}
// NFAEndOfInputNode
NFAEndOfInputNode::NFAEndOfInputNode(const bool lookForTerm) : term(lookForTerm) { }
int NFAEndOfInputNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int len = (int)str.size();
if (curInd == len) return next->match(str, matcher, curInd, depth + 1);
else if (term)
{
if (curInd == len - 1 && (str[curInd] == '\r' || str[curInd] == '\n'))
{
return next->match(str, matcher, curInd, depth + 1);
}
else if (curInd == len - 2 && str.substr(curInd, 2) == "\r\n")
{
return next->match(str, matcher, curInd, depth + 1);
}
}
return -1;
}
void NFAEndOfInputNode::print(const int indent)
{
printf("%*c%s(term=%s)\n", indent * 2, ' ', typeid(*this).name(), term ? "true" : "false");
if (next) next->print(indent);
}
// NFAWordBoundaryNode
NFAWordBoundaryNode::NFAWordBoundaryNode(const bool positive) : pos(positive) { }
int NFAWordBoundaryNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
#define is_alpha(x) (((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))
int len = (int)str.size();
bool ok = 0;
char c1 = (curInd - 1 < len) ? str[curInd - 1] : -1;
char c2 = (curInd < len) ? str[curInd ] : -1;
if (curInd == len) return next->match(str, matcher, curInd, depth + 1);
if (is_alpha(c1) ^ is_alpha(c2)) ok = 1;
if (ok && pos) return next->match(str, matcher, curInd, depth + 1);
return -1;
#undef is_alpha
}
void NFAWordBoundaryNode::print(const int indent)
{
printf("%*c%s(pos=%s)\n", indent * 2, ' ', typeid(*this).name(), pos ? "true" : "false");
if (next) next->print(indent);
}
// NFAEndOfMatchNode
NFAEndOfMatchNode::NFAEndOfMatchNode() { }
int NFAEndOfMatchNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
if (curInd == matcher->lm) return next->match(str, matcher, curInd, depth + 1);
return -1;
}
// NFAGroupHeadNode
NFAGroupHeadNode::NFAGroupHeadNode(const int groupIndex) : gi(groupIndex) { }
int NFAGroupHeadNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ret, o = matcher->starts[gi];
matcher->starts[gi] = curInd;
ret = next->match(str, matcher, curInd, depth + 1);
if (ret < 0) matcher->starts[gi] = o;
return ret;
}
void NFAGroupHeadNode::print(const int indent)
{
printf("%*c%s(gi=%d)\n", indent * 2, ' ', typeid(*this).name(), gi);
if (next) next->print(indent);
}
// NFAGroupTailNode
NFAGroupTailNode::NFAGroupTailNode(const int groupIndex) : gi(groupIndex) { }
int NFAGroupTailNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ret, o = matcher->ends[gi];
matcher->ends[gi] = curInd;
ret = next->match(str, matcher, curInd, depth + 1);
if (ret < 0) matcher->ends[gi] = o;
return ret;
}
void NFAGroupTailNode::print(const int indent)
{
printf("%*c%s(gi=%d)\n", indent * 2, ' ', typeid(*this).name(), gi);
if (next) next->print(indent);
}
// NFAGroupLoopPrologueNode
NFAGroupLoopPrologueNode::NFAGroupLoopPrologueNode(const int groupIndex) : gi(groupIndex) { }
int NFAGroupLoopPrologueNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ret, o1 = matcher->groups[gi], o2 = matcher->groupPos[gi], o3 = matcher->groupIndeces[gi];
matcher->groups[gi] = 0;
matcher->groupPos[gi] = 0;
matcher->groupIndeces[gi] = -1;
ret = next->match(str, matcher, curInd, depth + 1);
if (ret < 0)
{
matcher->groups[gi] = o1;
matcher->groupPos[gi] = o2;
matcher->groupIndeces[gi] = o3;
}
return ret;
}
void NFAGroupLoopPrologueNode::print(const int indent)
{
printf("%*c%s(gi=%d)\n", indent * 2, ' ', typeid(*this).name(), gi);
if (next) next->print(indent);
}
// NFAGroupLoopNode
NFAGroupLoopNode::NFAGroupLoopNode(NFANode * internal, const int minMatch, const int maxMatch,
const int groupIndex, const int matchType)
{
inner = internal;
min = minMatch;
max = maxMatch;
gi = groupIndex;
type = matchType;
}
void NFAGroupLoopNode::findAllNodes(std::map<NFANode*, bool> & soFar)
{
if (inner) inner->findAllNodes(soFar);
NFANode::findAllNodes(soFar);
}
int NFAGroupLoopNode::match(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
bool b = (curInd > matcher->groupIndeces[gi]);
if (b && matcher->groups[gi] < min)
{
++matcher->groups[gi];
int o = matcher->groupIndeces[gi];
matcher->groupIndeces[gi] = curInd;
int ret = inner->match(str, matcher, curInd, depth + 1);
if (ret < 0)
{
matcher->groupIndeces[gi] = o;
--matcher->groups[gi];
}
return ret;
}
else if (!b || matcher->groups[gi] >= max)
{
return next->match(str, matcher, curInd, depth + 1);
}
else
{
switch (type)
{
case 0: return matchGreedy(str, matcher, curInd, depth + 1);
case 1: return matchLazy(str, matcher, curInd, depth + 1);
case 2: return matchPossessive(str, matcher, curInd, depth + 1);
}
}
return -1;
}
int NFAGroupLoopNode::matchGreedy(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int o = matcher->groupIndeces[gi]; // save our info for backtracking
matcher->groupIndeces[gi] = curInd; // move along
++matcher->groups[gi];
int ret = inner->match(str, matcher, curInd, depth + 1); // match internally
if (ret < 0)
{ // if we failed, then restore info and match next
--matcher->groups[gi];
matcher->groupIndeces[gi] = o;
ret = next->match(str, matcher, curInd, depth + 1);
}
return ret;
}
int NFAGroupLoopNode::matchLazy(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int ret = next->match(str, matcher, curInd, depth + 1); // be lazy, just go on
if (ret < 0)
{
int o = matcher->groupIndeces[gi]; // save info for backtracking
matcher->groupIndeces[gi] = curInd; // advance our position
++matcher->groups[gi];
ret = inner->match(str, matcher, curInd, depth + 1); // match our internal stuff
if (ret < 0) // if we failed, then restore the info
{
--matcher->groups[gi];
matcher->groupIndeces[gi] = o;
}
}
return ret;
}
int NFAGroupLoopNode::matchPossessive(const std::string & str, Matcher * matcher, const int curInd, const int depth) const
{
int o = matcher->groupIndeces[gi]; // save info for backtracking
matcher->groupPos[gi] = matcher->groups[gi]; // set a flag stating we have matcher at least this much
matcher->groupIndeces[gi] = curInd; // move along
++matcher->groups[gi];
int ret = inner->match(str, matcher, curInd, depth + 1); // try and match again
if (ret < 0)
{ // if we fail, back off, but to an extent
--matcher->groups[gi];
matcher->groupIndeces[gi] = o;
if (matcher->groups[gi] == matcher->groupPos[gi]) ret = next->match(str, matcher, curInd, depth + 1);
}
return ret;
}
void NFAGroupLoopNode::print(const int indent)
{
printf("%*c%s(gi=%d, min=%d, max=%d, type=%s)\n", indent * 2, ' ', typeid(*this).name(), gi, min, max, type == 0 ? "greedy" : type == 1 ? "reluctant" : "possessive");
if (next) next->print(indent);
}
#ifdef _WIN32
#pragma warning(pop)
#endif
src/main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <memory>
#include "nfw.h"
using namespace std;
int main(int argc, char *argv[])
{
auto_ptr<nfw> nfwvar(new nfw(argc, argv));
if (nfwvar->isValid())
{
return 0;
} else {
cout << "Invalid rule!" << endl;
cout << nfwvar->getFalidRule() << endl;
return 1;
}
}
src/nfw.cpp
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
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <sstream>
#include <fstream>
#include "regexp/Pattern.h"
#include "regexp/Matcher.h"
#include "nfw.h"
using namespace std;
nfw::nfw(int argc, char *argv[])
{
for (int i = 0; i<argc; i++)
this->paramters.push_back(argv[i]);
this->populateGrammar();
this->parseArguments();
}
void nfw::parseArguments()
{
vector<string> rule_arr;
vector<string> words;
ifstream rulefile;
string line;
string rule;
if (this->paramters.size() == 1)
{
cerr << "Wrong number of arguments" << endl;
} else if ( this->paramters.size() == 2 && this->paramters.at(1) == "help" )
{
cout << "Some help information..." << endl;
this->valid = true;
} else if ( this->paramters.size() == 2 && (this->paramters.at(1) == "version" || this->paramters.at(1) == "ver" ) )
{
cout << "nfw version - " << NFW_VERSION << endl;
cout << "regex library by Jeff Stuart (GPL) http://freshmeat.net/projects/cpp_regex/" << endl;
this->valid = true;
} else if ( this->paramters.size() == 3 && this->paramters.at(1) == "file" ) {
//open file
rulefile.open(this->paramters.at(2).c_str());
if (rulefile.is_open())
{
while (! rulefile.eof() )
{
getline(rulefile, line);
Pattern * p = Pattern::compile("([a-z0-9.\\-])+ (\\w|\"([^\"]*)\")+");
rule_arr = p->findAll(line);
delete p;
this->split(line, ' ', words);
if (words.at(0) == "custom")
{
//this->customRule(rule);
for(unsigned int i = 1; i < words.size(); i++)
{
cout << words.at(i) << " ";
}
cout << endl;
} else {
if (this->validateRules(rule_arr))
{
this->valid = true;
this->parseRule(rule_arr);
} else {
this->valid = false;
}
}
words.clear();
rule_arr.clear();
}
rulefile.close();
}
} else if ( this->paramters.size() > 3) {
// parse rule from parameter
for(unsigned int i = 1; i < this->paramters.size(); i++)
{
if (i == this->paramters.size())
rule += this->paramters.at(i);
else
rule += this->paramters.at(i) + " ";
}
Pattern * p = Pattern::compile("([a-z0-9.\\-])+ (\\w|\"([^\"]*)\")+");
rule_arr = p->findAll(rule);
delete p;
this->split(rule, ' ', words);
if (words.at(0) == "custom")
{
//this->customRule(rule);
for(unsigned int i = 1; i < words.size(); i++)
{
cout << words.at(i) << " ";
}
cout << endl;
} else {
if (this->validateRules(rule_arr))
{
this->valid = true;
this->parseRule(rule_arr);
} else {
this->valid = false;
}
}
} else {
cerr << "Wrong number of arguments" << endl;
}
}
void nfw::parseRule(vector<string>& rule_arr)
{
// Parses a single rule
string p1;
string p2;
string rule = "";
string act = "";
string chain = "";
vector<string> parts;
auto_ptr<Pattern> split(Pattern::compile("([a-z0-9.\\-]|\\w|\"([^\"]*)\")+"));
auto_ptr<Pattern> action(Pattern::compile("(drop|deny|accept|log)"));
auto_ptr<Pattern> ip(Pattern::compile("(?:\\d{1,3}\\.){3}\\d{1,3}"));
auto_ptr<Pattern> iprange(Pattern::compile("(?:\\d{1,3}\\.){3}\\d{1,3}-(?:\\d{1,3}\\.){3}\\d{1,3}"));
auto_ptr<Pattern> port(Pattern::compile("(\\d)*"));
//auto_ptr<Matcher> actionmatch = action->createMatcher();
//auto_ptr<Matcher> ipmatch = ip->createMatcher();
//auto_ptr<Matcher> iprangematch = iprange->createMatcher();
for(unsigned int i = 0; i < rule_arr.size(); i++)
{
parts = split->findAll(rule_arr.at(i));
//this->split(rule_arr.at(i), ' ', parts);
//rule_arr.spl
p1 = parts.at(0);
p2 = parts.at(1);
parts.clear();
Matcher * actionmatch = action->createMatcher(p1);
Matcher * ipmatch = ip->createMatcher(p1);
Matcher * iprangematch = iprange->createMatcher(p1);
Matcher * portmatch = port->createMatcher(p1);
if (actionmatch->matches())
{
act = p1;
chain = p2;
} else if ( iprangematch->matches() )
{
rule += "-m iprange ";
if (p2 == "source")
rule += "--src-range ";
else
rule += "--dst-range ";
rule += p1 + " ";
} else if ( ipmatch->matches() )
{
if (p2 == "source")
rule += "-s ";
else
rule += "-d ";
rule += p1 + " ";
} else if ( portmatch->matches() )
{
if (p2 == "source")
rule += "--sport ";
else
rule += "--dport ";
rule += p1 + " ";
} else {
//parse the other rules that we won't bother matching with regex
if (p1 == "comment")
{
//strip qoutes if exists
if (p2.at(0) == '"')
{
p2.erase(0,1);
p2.erase(p2.size() - 1, 1);
}
//p2.replace(p2.find("\""), 1, "");
//p2.replace(p2.find("\""), 1, "");
rule += "-m comment --comment \"" + p2 + "\" ";
} else if (p1 == "protocol")
{
rule += "-p " + p2 + " ";
}
}
delete actionmatch;
delete ipmatch;
delete iprangematch;
}
transform(chain.begin(), chain.end(), chain.begin(), ::toupper);
transform(act.begin(), act.end(), act.begin(), ::toupper);
cout << "-A " << chain << " " << rule << "-j " << act << endl;
}
void nfw::populateGrammar()
{
// It doesn't seem to like (word|word) regex syntax, perhaps time to find a new regex library?
//this->grammar.push_back("(\\w)* (input|output|forward){1}"); // <action> <chain>
this->grammar.push_back("(\\w)* (\\w)*"); // <action> <chain>
this->grammar.push_back("(?:\\d{1,3}\\.){3}\\d{1,3} (source|destination)"); // <ip> =: <ip_addr> <direction>
this->grammar.push_back("(?:\\d{1,3}\\.){3}\\d{1,3}-(?:\\d{1,3}\\.){3}\\d{1,3} (source|destitation)"); // <iprange> =: <ip_addr>-<ip_addr> <direction>
//this->grammar.push_back("(\\d)* (source|destitation)");//<port> =: # <direction>
//this->grammar.push_back("recent (day|year|month)-(\\d)*-(\\d)*"); // <recent> =: recent <time>-#-#
this->grammar.push_back("(\\d)* (\\w)*");//<port> =: # <direction>
this->grammar.push_back("recent (\\w)*-(\\d)*-(\\d)*"); // <recent> =: recent <time>-#-#
this->grammar.push_back("name (\\w){1}"); //<name> =: name <string>
this->grammar.push_back("comment (\\w|\"([^\"]*)\")+"); //<comment> =: comment <string>
this->grammar.push_back("protocol (tcp|udp)"); //<protocol> =: protocol ( tcp | udp )
this->grammar.push_back("cstate (new|related|established|invalid)"); // <cstate> =: cstate { NEW | RELATED | ESTABLISHED | INVALID }
this->grammar.push_back("state (new|related|established|invalid)"); // <state> =: state { NEW | RELATED | ESTABLISHED | INVALID }
}
bool nfw::isValid()
{
return this->valid;
}
string nfw::getFalidRule()
{
return this->failedrule;
}
bool nfw::validateRules(vector<std :: string> & rule_arr)
{
for(unsigned int i = 0; i < rule_arr.size(); i++)
{
bool goodrule = false;
for (unsigned int x = 0; x < this->grammar.size(); x++)
{
Pattern * grammar_pat = Pattern::compile(this->grammar.at(x));
Matcher * grammar_match = grammar_pat->createMatcher(rule_arr.at(i));
if (grammar_match->matches())
{
goodrule = true;
break;
}
delete grammar_pat;
delete grammar_match;
}
if (goodrule == false)
{
this->failedrule = rule_arr.at(i);
return false;
}
}
return true;
}
void nfw::split(const std::string &s, char delim, std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
src/nfw.h
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
#ifndef NFW_H
#define NFW_H
#include <string>
#include <vector>
#define NFW_VERSION "1.1-4"
class nfw
{
private:
std::vector<std::string> paramters;
std::vector<std::string> grammar;
bool valid;
std::string failedrule;
public:
nfw(int, char*[]);
void parseArguments();
void parseRule(std::vector<std::string>&);
void populateGrammar();
bool isValid();
std::string getFalidRule();
bool validateRules(std::vector<std::string>&);
void split(const std::string &s, char delim, std::vector<std::string> &elems);
};
#endif
src/regexp/Matcher.h
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
#ifndef __MATCHER_H__
#define __MATCHER_H__
#include <string>
#include <vector>
class Vector;
class NFANode;
class NFAStartNode;
class NFAEndNode;
class NFAGroupHeadNode;
class NFAGroupLoopNode;
class NFAGroupLoopPrologueNode;
class NFAGroupTailNode;
class NFALookBehindNode;
class NFAStartOfLineNode;
class NFAEndOfLineNode;
class NFAEndOfMatchNode;
class NFAReferenceNode;
class Pattern;
/**
A matcher is a non thread-safe object used to scan strings using a given
{@link Pattern Pattern} object. Using a <code>Matcher</code> is the preferred
method for scanning strings. Matchers are not thread-safe. Matchers require
very little dynamic memory, hence one is encouraged to create several
instances of a matcher when necessary as opposed to sharing a single instance
of a matcher.
<p>
The most common methods needed by the matcher are <code>matches</code>,
<code>findNextMatch</code>, and <code>getGroup</code>. <code>matches</code>
and <code>findNextMatch</code> both return success or failure, and further
details can be gathered from their documentation.
<p>
Unlike Java's <code>Matcher</code>, this class allows you to change the string
you are matching against. This provides a small optimization, since you no
longer need multiple matchers for a single pattern in a single thread.
<p>
This class also provides an extremely handy method for replacing text with
captured data via the <code>replaceWithGroups</code> method. A typical
invocation looks like:
<pre>
char buf[10000];
std::string str = "\\5 (user name \\1) uses \\7 for his/her shell and \\6 is their home directory";
FILE * fp = fopen("/etc/passwd", "r");
Pattern::registerPattern("entry", "[^:]+");
Pattern * p = Pattern::compile("^({entry}):({entry}):({entry}):({entry}):({entry}):({entry}):({entry})$",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pattern::MULTILINE_MATCHING | Pattern::UNIX_LINE_MODE);
Matcher * m = p->createMatcher("");
while (fgets(buf, 9999, fp))
{
&nbsp;&nbsp;m->setString(buf);
&nbsp;&nbsp;if (m->matches())
&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;printf("%s\n", m->replaceWithGroups(str).c_str());
&nbsp;&nbsp;}
}
fclose(fp);
</pre>
Calling any of the following functions before first calling
<code>matches</code>, <code>findFirstMatch</code>, or
<code>findNextMatch</code> results in undefined behavior and may cause your
program to crash.
<code>
<ul>
<li>replaceWithGroups</code>
<li>getStartingIndex</li>
<li>getEndingIndex</li>
<li>getGroup</li>
<li>getGroups</li>
</ul>
</code>
<p>
The function <code>findFirstMatch</code> will attempt to find the first match
in the input string. The same results can be obtained by first calling
<code>reset</code> followed by <code>findNextMatch</code>.
<p>
To eliminate the necessity of looping through a string to find all the
matching substrings, <code>findAll</code> was created. The function will find
all matching substrings and return them in a <code>vector</code>. If you need
to examine specific capture groups within the substrings, then this method
should not be used.
@author Jeffery Stuart
@since March 2003, Stable Since November 2004
@version 1.07.00
@memo Mutable object used on instances of a Pattern class
*/
class Matcher
{
friend class NFANode;
friend class NFAStartNode;
friend class NFAEndNode;
friend class NFAGroupHeadNode;
friend class NFAGroupLoopNode;
friend class NFAGroupLoopPrologueNode;
friend class NFAGroupTailNode;
friend class NFALookBehindNode;
friend class NFAStartOfLineNode;
friend class NFAEndOfLineNode;
friend class NFAEndOfMatchNode;
friend class NFAReferenceNode;
friend class Pattern;
private:
/**
Creates a new matcher object against <code>text</code> using
<code>pattern</code>.
@param pattern The pattern with which to search
@param text The text in which to search
*/
Matcher(Pattern * pattern, const std::string & text);
protected:
/// The pattern we use to match
Pattern * pat;
/// The string in which we are matching
std::string str;
/// The starting point of our match
int start;
/// An array of the starting positions for each group
int * starts;
/// An array of the ending positions for each group
int * ends;
/// An array of private data used by NFANodes during matching
int * groups;
/// An array of private data used by NFANodes during matching
int * groupIndeces;
/// An array of private data used by NFANodes during matching
int * groupPos;
/// The ending index of the last match
int lm;
/// The number of capturing groups we have
int gc;
/// The number of non-capturing groups we havew
int ncgc;
/// Whether or not we have matched something (used only by findFirstMatch and findNextMatch)
int matchedSomething;
/// The flags with which we were made
unsigned long flags;
/// Called by reset to clear the group arrays
void clearGroups();
public:
/// Used internally by match to signify we want the entire string matched
const static int MATCH_ENTIRE_STRING;
public:
/// Cleans up the dynamic memory used by this matcher
~Matcher();
/**
Replaces the contents of <code>str</code> with the appropriate captured
text. <code>str</code> should have at least one back reference, otherwise
this function does nothing.
@param str The string in which to replace text
@return A string with all backreferences appropriately replaced
*/
std::string replaceWithGroups(const std::string & str);
/**
The flags currently being used by the matcher.
@return Zero
*/
unsigned long getFlags() const;
/**
The text being searched by the matcher.
@return the text being searched by the matcher.
*/
std::string getText() const;
/**
Scans the string from start to finish for a match. The entire string must
match for this function to return success. Group variables are
appropriately set and can be queried after this function returns.
@return Success if and only if the entire string matches the pattern
*/
bool matches();
/**
Scans the string for the first substring matching the pattern. The entire
string does not necessarily have to match for this function to return
success. Group variables are appropriately set and can be queried after
this function returns.
@return Success if any substring matches the specified pattern
*/
bool findFirstMatch();
/**
Scans the string for the next substring matching the pattern. If no calls
have been made to findFirstMatch of findNextMatch since the last call to
reset, matches, or setString, then this function's behavior results to
that of findFirstMatch.
@return Success if another substring can be found that matches the pattern
*/
bool findNextMatch();
/**
Returns a vector of every substring in order which matches the given
pattern.
@return Every substring in order which matches the given pattern
*/
std::vector<std::string> findAll();
/**
Resets the internal state of the matcher
*/
void reset();
/**
Same as getText. Left n for backwards compatibilty with old source code
@return Returns the string that is currently being used for matching
*/
inline std::string getString() const { return str; }
/**
Sets the string to scan
@param newStr The string to scan for subsequent matches
*/
inline void setString(const std::string & newStr) { str = newStr; reset(); }
/**
Returns the starting index of the specified group.
@param groupNum The group to query
@return The starting index of the group if it was matched, -1 for an
invalid group or if the group was not matched
*/
int getStartingIndex(const int groupNum = 0) const;
/**
Returns the ending index of the specified group.
@param groupNum The group to query
@return The ending index of the group if it was matched, -1 for an
invalid group or if the group was not matched
*/
int getEndingIndex(const int groupNum = 0) const;
/**
Returns the specified group. An empty string ("") does not necessarily
mean the group was not matched. A group such as (a*b?) could be matched by
a zero length. If an empty string is returned, getStartingIndex can be
called to determine if the group was actually matched.
@param groupNum The group to query
@return The text of the group
*/
std::string getGroup(const int groupNum = 0) const;
/**
Returns every capture group in a vector
@param includeGroupZero Whether or not include capture group zero
@return Every capture group
*/
std::vector<std::string> getGroups(const bool includeGroupZero = 0) const;
};
#endif
src/regexp/Pattern.h
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
#ifndef __PATTERN_H__
#define __PATTERN_H__
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
#include <vector>
#include <string>
#include <map>
class Matcher;
class NFANode;
class NFAQuantifierNode;
/**
This pattern class is very similar in functionality to Java's
java.util.regex.Pattern class. The pattern class represents an immutable
regular expression object. Instead of having a single object contain both the
regular expression object and the matching object, instead the two objects are
split apart. The {@link Matcher Matcher} class represents the maching
object.
The Pattern class works primarily off of "compiled" patterns. A typical
instantiation of a regular expression looks like:
<pre>
Pattern * p = Pattern::compile("a*b");
Matcher * m = p->createMatcher("aaaaaab");
if (m->matches()) ...
</pre>
However, if you do not need to use a pattern more than once, it is often times
okay to use the Pattern's static methods insteads. An example looks like this:
<pre>
if (Pattern::matches("a*b", "aaaab")) { ... }
</pre>
This class does not currently support unicode. The unicode update for this
class is coming soon.
This class is partially immutable. It is completely safe to call createMatcher
concurrently in different threads, but the other functions (e.g. split) should
not be called concurrently on the same <code>Pattern</code>.
<table border="0" cellpadding="1" cellspacing="0">
<tr align="left" bgcolor="#CCCCFF">
<td>
<b>Construct</b>
</td>
<td>
<b>Matches</b>
</th>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Characters</b>
</td>
</tr>
<tr>
<td>
<code><i>x</i></code>
</td>
<td>
The character <code><i>x</i></code>
</td>
</tr>
<tr>
<td>
<code>\\</code>
</td>
<td>
The character <code>\</code>
</td>
</tr>
<tr>
<td>
<code>\0<i>nn</i></code>
</td>
<td>
The character with octal ASCII value <code><i>nn</i></code>
</td>
</tr>
<tr>
<td>
<code>\0<i>nnn</i></code>
</td>
<td>
The character with octal ASCII value <code><i>nnn</i></code>
</td>
</tr>
<tr>
<td>
<code>\x<i>hh</i></code>
</td>
<td>
The character with hexadecimal ASCII value <code><i>hh</i></code>
</td>
</tr>
<tr>
<td>
<code>\t</code>
</td>
<td>
A tab character
</td>
</tr>
<tr>
<td>
<code>\r</code>
</td>
<td>
A carriage return character
</td>
</tr>
<tr>
<td>
<code>\n</code>
</td>
<td>
A new-line character
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td>
<b>Character Classes</b>
</td>
</tr>
<tr>
<td>
<code>[abc]</code>
</td>
<td>
Either <code>a</code>, <code>b</code>, or <code>c</code>
</td>
</tr>
<tr>
<td>
<code>[^abc]</code>
</td>
<td>
Any character but <code>a</code>, <code>b</code>, or <code>c</code>
</td>
</tr>
<tr>
<td>
<code>[a-zA-Z]</code>
</td>
<td>
Any character ranging from <code>a</code> thru <code>z</code>, or
<code>A</code> thru <code>Z</code>
</td>
</tr>
<tr>
<td>
<code>[^a-zA-Z]</code>
</td>
<td>
Any character except those ranging from <code>a</code> thru
<code>z</code>, or <code>A</code> thru <code>Z</code>
</td>
</tr>
<tr>
<td>
<code>[a\-z]</code>
</td>
<td>
Either <code>a</code>, <code>-</code>, or <code>z</code>
</td>
</tr>
<tr>
<td>
<code>[a-z[A-Z]]</code>
</td>
<td>
Same as <code>[a-zA-Z]</code>
</td>
</tr>
<tr>
<td>
<code>[a-z&&[g-i]]</code>
</td>
<td>
Any character in the intersection of <code>a-z</code> and
<code>g-i</code>
</td>
</tr>
<tr>
<td>
<code>[a-z&&[^g-i]]</code>
</td>
<td>
Any character in <code>a-z</code> and not in <code>g-i</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Prefefined character classes</b>
</td>
</tr>
<tr>
<td>
<code><b>.</b></code>
</td>
<td>
Any character. Multiline matching must be compiled into the pattern for
<code><b>.</b></code> to match a <code>\r</code> or a <code>\n</code>.
Even if multiline matching is enabled, <code><b>.</b></code> will not
match a <code>\r\n</code>, only a <code>\r</code> or a <code>\n</code>.
</td>
</tr>
<tr>
<td>
<code>\d</code>
</td>
<td>
<code>[0-9]</code>
</td>
</tr>
<tr>
<td>
<code>\D</code>
</td>
<td>
<code>[^\d]</code>
</td>
</tr>
<tr>
<td>
<code>\s</code>
</td>
<td>
<code>[&nbsp;\t\r\n\x0B]</code>
</td>
</tr>
<tr>
<td>
<code>\S</code>
</td>
<td>
<code>[^\s]</code>
</td>
</tr>
<tr>
<td>
<code>\w</code>
</td>
<td>
<code>[a-zA-Z0-9_]</code>
</td>
</tr>
<tr>
<td>
<code>\W</code>
</td>
<td>
<code>[^\w]</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>POSIX character classes
</td>
</tr>
<tr>
<td>
<code>\p{Lower}</code>
</td>
<td>
<code>[a-z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Upper}</code>
</td>
<td>
<code>[A-Z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{ASCII}</code>
</td>
<td>
<code>[\x00-\x7F]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Alpha}</code>
</td>
<td>
<code>[a-zA-Z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Digit}</code>
</td>
<td>
<code>[0-9]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Alnum}</code>
</td>
<td>
<code>[\w&&[^_]]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Punct}</code>
</td>
<td>
<code>[!"#$%&'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~]</code>
</td>
</tr>
<tr>
<td>
<code>\p{XDigit}</code>
</td>
<td>
<code>[a-fA-F0-9]</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Boundary Matches</b>
</td>
</tr>
<tr>
<td>
<code>^</code>
</td>
<td>
The beginning of a line. Also matches the beginning of input.
</td>
</tr>
<tr>
<td>
<code>$</code>
</td>
<td>
The end of a line. Also matches the end of input.
</td>
</tr>
<tr>
<td>
<code>\b</code>
</td>
<td>
A word boundary
</td>
</tr>
<tr>
<td>
<code>\B</code>
</td>
<td>
A non word boundary
</td>
</tr>
<tr>
<td>
<code>\A</code>
</td>
<td>
The beginning of input
</td>
</tr>
<tr>
<td>
<code>\G</code>
</td>
<td>
The end of the previous match. Ensures that a "next" match will only
happen if it begins with the character immediately following the end of
the "current" match.
</td>
</tr>
<tr>
<td>
<code>\Z</code>
</td>
<td>
The end of input. Will also match if there is a single trailing
<code>\r\n</code>, a single trailing <code>\r</code>, or a single
trailing <code>\n</code>.
</td>
</tr>
<tr>
<td>
<code>\z</code>
</td>
<td>
The end of input
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Greedy Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x?</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x+</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Possessive Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x?+</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*+</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x++</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}+</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}+</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}+</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}+</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Reluctant Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x??</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*?</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x+?</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}?</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}?</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}?</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}?</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Operators</b>
</td>
</tr>
<tr>
<td>
<code><i>xy</i></code>
</td>
<td>
<code><i>x</i></code> then <code><i>y</i></code>
</td>
</tr>
<tr>
<td>
<code><i>x</i></code>|<code><i>y</i></code>
</td>
<td>
<code><i>x</i></code> or <code><i>y</i></code>
</td>
</tr>
<tr>
<td>
<code>(<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code> as a capturing group
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Quoting</b>
</td>
</tr>
<tr>
<td>
<code>\Q</code>
</td>
<td>
Nothing, but treat every character (including \s) literally until a
matching <code>\E</code>
</td>
</tr>
<tr>
<td>
<code>\E</code>
</td>
<td>
Nothing, but ends its matching <code>\Q</code>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Special Constructs</b>
</td>
</tr>
<tr>
<td>
<code>(?:<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, but not as a capturing group
</td>
</tr>
<tr>
<td>
<code>(?=<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via positive lookahead. This means that the
expression will match only if it is trailed by <code><i>x</i></code>.
It will not "eat" any of the characters matched by
<code><i>x</i></code>.
</td>
</tr>
<tr>
<td>
<code>(?!<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via negative lookahead. This means that the
expression will match only if it is not trailed by
<code><i>x</i></code>. It will not "eat" any of the characters
matched by <code><i>x</i></code>.
</td>
</tr>
<tr>
<td>
<code>(?<=<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via positive lookbehind. <code><i>x</i></code>
cannot contain any quantifiers.
</td>
</tr>
<tr>
<td>
<code>(?<!<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via negative lookbehind. <code><i>x</i></code>
cannot contain any quantifiers.
</td>
</tr>
<tr>
<td>
<code>(?><i>x</i>)</code>
</td>
<td>
<code><i>x</i>{1}+</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Registered Expression Matching</b>
</td>
</tr>
<tr>
<td>
<code>{<i>x</i>}</code>
</td>
<td>
The registered pattern <code><i>x</i></code>
</td>
</tr>
</table>
<hr>
<i>Begin Text Extracted And Modified From java.util.regex.Pattern documentation</i>
<h4> Backslashes, escapes, and quoting </h4>
<p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
constructs, as defined in the table above, as well as to quote characters
that otherwise would be interpreted as unescaped constructs. Thus the
expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
left brace.
<p> It is an error to use a backslash prior to any alphabetic character that
does not denote an escaped construct; these are reserved for future
extensions to the regular-expression language. A backslash may be used
prior to a non-alphabetic character regardless of whether that character is
part of an unescaped construct.
<p>It is necessary to double backslashes in string literals that represent
regular expressions to protect them from interpretation by a compiler. The
string literal <tt>"&#92;b"</tt>, for example, matches a single backspace
character when interpreted as a regular expression, while
<tt>"&#92;&#92;b"</tt> matches a word boundary. The string litera
<tt>"&#92;(hello&#92;)"</tt> is illegal and leads to a compile-time error;
in order to match the string <tt>(hello)</tt> the string literal
<tt>"&#92;&#92;(hello&#92;&#92;)"</tt> must be used.
<h4> Character Classes </h4>
<p> Character classes may appear within other character classes, and
may be composed by the union operator (implicit) and the intersection
operator (<tt>&amp;&amp;</tt>).
The union operator denotes a class that contains every character that is
in at least one of its operand classes. The intersection operator
denotes a class that contains every character that is in both of its
operand classes.
<p> The precedence of character-class operators is as follows, from
highest to lowest:
<blockquote><table border="0" cellpadding="1" cellspacing="0"
summary="Precedence of character class operators.">
<tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><tt>\x</tt></td></tr>
<tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Range</td>
<td><tt>a-z</tt></td></tr>
<tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Grouping</td>
<td><tt>[...]</tt></td></tr>
<tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Intersection</td>
<td><tt>[a-z&&[aeiou]]</tt></td></tr>
<tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Union</td>
<td><tt>[a-e][i-u]<tt></td></tr>
</table></blockquote>
<p> Note that a different set of metacharacters are in effect inside
a character class than outside a character class. For instance, the
regular expression <tt>.</tt> loses its special meaning inside a
character class, while the expression <tt>-</tt> becomes a range
forming metacharacter.
<a name="lt">
<a name="cg">
<h4> Groups and capturing </h4>
<p> Capturing groups are numbered by counting their opening parentheses from
left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
are four such groups: </p>
<blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
<tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>((A)(B(C)))</tt></td></tr>
<tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(A)</tt></td></tr>
<tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(B(C))</tt></td></tr>
<tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(C)</tt></td></tr>
</table></blockquote>
<p> Group zero always stands for the entire expression.
<p> Capturing groups are so named because, during a match, each subsequence
of the input sequence that matches such a group is saved. The captured
subsequence may be used later in the expression, via a back reference, and
may also be retrieved from the matcher once the match operation is complete.
<p> The captured input associated with a group is always the subsequence
that the group most recently matched. If a group is evaluated a second time
because of quantification then its previously-captured value, if any, will
be retained if the second evaluation fails. Matching the string
<tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
group two set to <tt>"b"</tt>. All captured input is discarded at the
beginning of each match.
<p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups
that do not capture text and do not count towards the group total.
<h4> Unicode support </h4>
<p> Coming Soon.
<h4> Comparison to Perl 5 </h4>
<p>The <code>Pattern</code> engine performs traditional NFA-based matching
with ordered alternation as occurs in Perl 5.
<p> Perl constructs not supported by this class: </p>
<ul>
<li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and
<tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
</p></li>
<li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
<li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
<li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
<tt>\L</tt>, and <tt>\U</tt>. </p></li>
<li><p> Embedded flags</p></li>
</ul>
<p> Constructs supported by this class but not by Perl: </p>
<ul>
<li><p> Possessive quantifiers, which greedily match as much as they can
and do not back off, even when doing so would allow the overall match to
succeed. </p></li>
<li><p> Character-class union and intersection as described
above.</p></li>
</ul>
<p> Notable differences from Perl: </p>
<ul>
<li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
as back references; a backslash-escaped number greater than <tt>9</tt> is
treated as a back reference if at least that many subexpressions exist,
otherwise it is interpreted, if possible, as an octal escape. In this
class octal escapes must always begin with a zero. In this class,
<tt>\1</tt> through <tt>\9</tt> are always interpreted as back
references, and a larger number is accepted as a back reference if at
least that many subexpressions exist at that point in the regular
expression, otherwise the parser will drop digits until the number is
smaller or equal to the existing number of groups or it is one digit.
</p></li>
<li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
where the last match left off. This functionality is provided implicitly
by the <CODE>Matcher</CODE> class: Repeated invocations of the
<code>find</code> method will resume where the last match left off,
unless the matcher is reset. </p></li>
<li><p> Perl is forgiving about malformed matching constructs, as in the
expression <tt>*a</tt>, as well as dangling brackets, as in the
expression <tt>abc]</tt>, and treats them as literals. This
class also strict and will not compile a pattern when dangling characters
are encountered.</p></li>
</ul>
<p> For a more precise description of the behavior of regular expression
constructs, please see <a href="http://www.oreilly.com/catalog/regex2/">
<i>Mastering Regular Expressions, 2nd Edition</i>, Jeffrey E. F. Friedl,
O'Reilly and Associates, 2002.</a>
</p>
<P>
<i>End Text Extracted And Modified From java.util.regex.Pattern documentation</i>
<hr>
@author Jeffery Stuart
@since November 24th, 2004
@version 1.08.00
@memo A class used to represent "PERL 5"-ish regular expressions
*/
class Pattern
{
friend class Matcher;
friend class NFANode;
friend class NFAQuantifierNode;
private:
/**
This constructor should not be called directly. Those wishing to use the
Pattern class should instead use the {@link compile compile} method.
@param rhs The pattern to compile
@memo Creates a new pattern from the regular expression in <code>rhs</code>.
*/
Pattern(const std::string & rhs);
protected:
/**
This currently is not used, so don't try to do anything with it.
@memo Holds all the compiled patterns for quick access.
*/
static std::map<std::string, Pattern *> compiledPatterns;
/**
Holds all of the registered patterns as strings. Due to certain problems
with compilation of patterns, especially with capturing groups, this seemed
to be the best way to do it.
*/
static std::map<std::string, std::pair<std::string, unsigned long> > registeredPatterns;
protected:
/**
Holds all the NFA nodes used. This makes deletion of a pattern, as well as
clean-up from an unsuccessful compile much easier and faster.
*/
std::map<NFANode*, bool> nodes;
/**
Used when methods like split are called. The matcher class uses a lot of
dynamic memeory, so having an instance increases speedup of certain
operations.
*/
Matcher * matcher;
/**
The front node of the NFA.
*/
NFANode * head;
/**
The actual regular expression we rerpesent
*/
std::string pattern;
/**
Flag used during compilation. Once the pattern is successfully compiled,
<code>error</code> is no longer used.
*/
bool error;
/**
Used during compilation to keep track of the current index into
<code>{@link pattern pattern}<code>. Once the pattern is successfully
compiled, <code>error</code> is no longer used.
*/
int curInd;
/**
The number of capture groups this contains.
*/
int groupCount;
/**
The number of non-capture groups this contains.
*/
int nonCapGroupCount;
/**
The flags specified when this was compiled.
*/
unsigned long flags;
protected:
/**
Raises an error during compilation. Compilation will cease at that point
and compile will return <code>NULL</code>.
*/
void raiseError();
/**
Convenience function for registering a node in <code>nodes</code>.
@param node The node to register
@return The registered node
*/
NFANode * registerNode(NFANode * node);
/**
Calculates the union of two strings. This function will first sort the
strings and then use a simple selection algorithm to find the union.
@param s1 The first "class" to union
@param s2 The second "class" to union
@return A new string containing all unique characters. Each character
must have appeared in one or both of <code>s1</code> and
<code>s2</code>.
*/
std::string classUnion (std::string s1, std::string s2) const;
/**
Calculates the intersection of two strings. This function will first sort
the strings and then use a simple selection algorithm to find the
intersection.
@param s1 The first "class" to intersect
@param s2 The second "class" to intersect
@return A new string containing all unique characters. Each character
must have appeared both <code>s1</code> and <code>s2</code>.
*/
std::string classIntersect (std::string s1, std::string s2) const;
/**
Calculates the negation of a string. The negation is the set of all
characters between <code>\x00</code> and <code>\xFF</code> not
contained in <code>s1</code>.
@param s1 The "class" to be negated.
@param s2 The second "class" to intersect
@return A new string containing all unique characters. Each character
must have appeared both <code>s1</code> and <code>s2</code>.
*/
std::string classNegate (std::string s1) const;
/**
Creates a new "class" representing the range from <code>low</code> thru
<code>hi</code>. This function will wrap if <code>low</code> &gt;
<code>hi</code>. This is a feature, not a buf. Sometimes it is useful
to be able to say [\x70-\x10] instead of [\x70-\x7F\x00-\x10].
@param low The beginning character
@param hi The ending character
@return A new string containing all the characters from low thru hi.
*/
std::string classCreateRange(char low, char hi) const;
/**
Extracts a decimal number from the substring of member-variable
<code>{@link pattern pattern}<code> starting at <code>start</code> and
ending at <code>end</code>.
@param start The starting index in <code>{@link pattern pattern}<code>
@param end The last index in <code>{@link pattern pattern}<code>
@return The decimal number in <code>{@link pattern pattern}<code>
*/
int getInt(int start, int end);
/**
Parses a <code>{n,m}</code> string out of the member-variable
<code>{@link pattern pattern}<code> stores the result in <code>sNum</code>
and <code>eNum</code>.
@param sNum Output parameter. The minimum number of matches required
by the curly quantifier are stored here.
@param eNum Output parameter. The maximum number of matches allowed
by the curly quantifier are stored here.
@return Success/Failure. Fails when the curly does not have the proper
syntax
*/
bool quantifyCurly(int & sNum, int & eNum);
/**
Tries to quantify the currently parsed group. If the group being parsed
is indeed quantified in the member-variable
<code>{@link pattern pattern}<code>, then the NFA is modified accordingly.
@param start The starting node of the current group being parsed
@param stop The ending node of the current group being parsed
@param gn The group number of the current group being parsed
@return The node representing the starting node of the group. If the
group becomes quantified, then this node is not necessarily
a GroupHead node.
*/
NFANode * quantifyGroup(NFANode * start, NFANode * stop, const int gn);
/**
Tries to quantify the last parsed expression. If the character was indeed
quantified, then the NFA is modified accordingly.
@param newNode The recently created expression node
@return The node representing the last parsed expression. If the
expression was quantified, <code>return value != newNode</code>
*/
NFANode * quantify(NFANode * newNode);
/**
Parses the current class being examined in
<code>{@link pattern pattern}</code>.
@return A string of unique characters contained in the current class being
parsed
*/
std::string parseClass();
/**
Parses the current POSIX class being examined in
<code>{@link pattern pattern}</code>.
@return A string of unique characters representing the POSIX class being
parsed
*/
std::string parsePosix();
/**
Returns a string containing the octal character being parsed
@return The string contained the octal value being parsed
*/
std::string parseOctal();
/**
Returns a string containing the hex character being parsed
@return The string contained the hex value being parsed
*/
std::string parseHex();
/**
Returns a new node representing the back reference being parsed
@return The new node representing the back reference being parsed
*/
NFANode * parseBackref();
/**
Parses the escape sequence currently being examined. Determines if the
escape sequence is a class, a single character, or the beginning of a
quotation sequence.
@param inv Output parameter. Whether or not to invert the returned class
@param quo Output parameter. Whether or not this sequence starts a
quotation.
@return The characters represented by the class
*/
std::string parseEscape(bool & inv, bool & quo);
/**
Parses a supposed registered pattern currently under compilation. If the
sequence of characters does point to a registered pattern, then the
registered pattern is appended to <code>*end<code>. The registered pattern
is parsed with the current compilation flags.
@param end The ending node of the thus-far compiled pattern
@return The new end node of the current pattern
*/
NFANode * parseRegisteredPattern(NFANode ** end);
/**
Parses a lookbehind expression. Appends the necessary nodes
<code>*end</code>.
@param pos Positive or negative look behind
@param end The ending node of the current pattern
@return The new end node of the current pattern
*/
NFANode * parseBehind(const bool pos, NFANode ** end);
/**
Parses the current expression and tacks on nodes until a \E is found.
@return The end of the current pattern
*/
NFANode * parseQuote();
/**
Parses <code>{@link pattern pattern}</code>. This function is called
recursively when an or (<code>|</code>) or a group is encountered.
@param inParen Are we currently parsing inside a group
@param inOr Are we currently parsing one side of an or (<code>|</code>)
@param end The end of the current expression
@return The starting node of the NFA constructed from this parse
*/
NFANode * parse(const bool inParen = 0, const bool inOr = 0, NFANode ** end = NULL, const int orGroup = 0, const bool inOrCap = false);
public:
/// We should match regardless of case
const static unsigned long CASE_INSENSITIVE;
/// We are implicitly quoted
const static unsigned long LITERAL;
/// @memo We should treat a <code><b>.</b></code> as [\x00-\x7F]
const static unsigned long DOT_MATCHES_ALL;
/** <code>^</code> and <code>$</code> should anchor to the beginning and
ending of lines, not all input
*/
const static unsigned long MULTILINE_MATCHING;
/** When enabled, only instances of <code>\n</codes> are recognized as
line terminators
*/
const static unsigned long UNIX_LINE_MODE;
/// The absolute minimum number of matches a quantifier can match (0)
const static int MIN_QMATCH;
/// The absolute maximum number of matches a quantifier can match (0x7FFFFFFF)
const static int MAX_QMATCH;
public:
/**
Call this function to compile a regular expression into a
<code>Pattern</code> object. Special values can be assigned to
<code>mode</code> when certain non-standard behaviors are expected from
the <code>Pattern</code> object.
@param pattern The regular expression to compile
@param mode A bitwise or of flags signalling what special behaviors are
wanted from this <code>Pattern</code> object
@return If successful, <code>compile</code> returns a <code>Pattern</code>
pointer. Upon failure, <code>compile</code> returns
<code>NULL</code>
*/
static Pattern * compile (const std::string & pattern,
const unsigned long mode = 0);
/**
Dont use this function. This function will compile a pattern, and cache
the result. This will eventually be used as an optimization when people
just want to call static methods using the same pattern over and over
instead of first compiling the pattern and then using the compiled
instance for matching.
@param pattern The regular expression to compile
@param mode A bitwise or of flags signalling what special behaviors are
wanted from this <code>Pattern</code> object
@return If successful, <code>compileAndKeep</code> returns a
<code>Pattern</code> pointer. Upon failure, <code>compile</code>
returns <code>NULL</code>.
*/
static Pattern * compileAndKeep (const std::string & pattern,
const unsigned long mode = 0);
/**
Searches through <code>replace</code> and replaces all substrings matched
by <code>pattern</code> with <code>str</code>. <code>str</code> may
contain backreferences (e.g. <code>\1</code>) to capture groups. A typical
invocation looks like:
<p>
<code>
Pattern::replace("(a+)b(c+)", "abcccbbabcbabc", "\\2b\\1");
</code>
<p>
which would replace <code>abcccbbabcbabc</code> with
<code>cccbabbcbabcba</code>.
@param pattern The regular expression
@param str The replacement text
@param replacementText The string in which to perform replacements
@param mode The special mode requested of the <code>Pattern</code>
during the replacement process
@return The text with the replacement string substituted where necessary
*/
static std::string replace (const std::string & pattern,
const std::string & str,
const std::string & replacementText,
const unsigned long mode = 0);
/**
Splits the specified string over occurrences of the specified pattern.
Empty strings can be optionally ignored. The number of strings returned is
configurable. A typical invocation looks like:
<p>
<code>
std::string str(strSize, '\0');<br>
FILE * fp = fopen(fileName, "r");<br>
fread((char*)str.data(), strSize, 1, fp);<br>
fclose(fp);<br>
<br>
std::vector&lt;std::string&gt; lines = Pattern::split("[\r\n]+", str, true);<br>
<br>
</code>
@param pattern The regular expression
@param replace The string to split
@param keepEmptys Whether or not to keep empty strings
@param limit The maximum number of splits to make
@param mode The special mode requested of the <code>Pattern</code>
during the split process
@return All substrings of <code>str</code> split across <code>pattern</code>.
*/
static std::vector<std::string> split (const std::string & pattern,
const std::string & str,
const bool keepEmptys = 0,
const unsigned long limit = 0,
const unsigned long mode = 0);
/**
Finds all the instances of the specified pattern within the string. You
should be careful to only pass patterns with a minimum length of one. For
example, the pattern <code>a*</code> can be matched by an empty string, so
instead you should pass <code>a+</code> since at least one character must
be matched. A typical invocation of <code>findAll</code> looks like:
<p>
<code>
std::vector&lt;td::string&gt; numbers = Pattern::findAll("\\d+", string);
</code>
<p>
@param pattern The pattern for which to search
@param str The string to search
@param mode The special mode requested of the <code>Pattern</code>
during the find process
@return All instances of <code>pattern</code> in <code>str</code>
*/
static std::vector<std::string> findAll (const std::string & pattern,
const std::string & str,
const unsigned long mode = 0);
/**
Determines if an entire string matches the specified pattern
@param pattern The pattern for to match
@param str The string to match
@param mode The special mode requested of the <code>Pattern</code>
during the replacement process
@return True if <code>str</code> is recognized by <code>pattern</code>
*/
static bool matches (const std::string & pattern,
const std::string & str,
const unsigned long mode = 0);
/**
Registers a pattern under a specific name for use in later compilations.
A typical invocation and later use looks like:
<p>
<code>
Pattern::registerPattern("ip", "(?:\\d{1,3}\\.){3}\\d{1,3}");<br>
Pattern * p1 = Pattern::compile("{ip}:\\d+");<br>
Pattern * p2 = Pattern::compile("Connection from ({ip}) on port \\d+");<br>
</code>
<p>
Multiple calls to <code>registerPattern</code> with the same
<code>name</code> will result in the pattern getting overwritten.
@param name The name to give to the pattern
@param pattern The pattern to register
@param mode Any special flags to use when compiling pattern
@return Success/Failure. Fails only if <code>pattern</code> has invalid
syntax
*/
static bool registerPattern(const std::string & name,
const std::string & pattern,
const unsigned long mode = 0);
/**
Clears the pattern registry
*/
static void unregisterPatterns();
/**
Don't use
*/
static void clearPatternCache();
/**
Searches through a string for the <code>n<sup>th</sup></code> match of the
given pattern in the string. Match indeces start at zero, not one.
A typical invocation looks like this:
<p>
<code>
std::pair&lt;std::string, int&gt; match = Pattern::findNthMatch("\\d{1,3}", "192.168.1.101:22", 1);<br>
printf("%s %i\n", match.first.c_str(), match.second);<br>
<br>
Output: 168 4<br>
<br>
@param pattern The pattern for which to search
@param str The string to search
@param matchNum Which match to find
@param mode Any special flags to use during the matching process
@return A string and an integer. The string is the string matched. The
integer is the starting location of the matched string in
<code>str</code>. You can check for success/failure by making sure
that the integer returned is greater than or equal to zero.
*/
static std::pair<std::string, int> findNthMatch (const std::string & pattern,
const std::string & str,
const int matchNum,
const unsigned long mode = 0);
public:
/**
Deletes all NFA nodes allocated during compilation
*/
~Pattern();
std::string replace (const std::string & str,
const std::string & replacementText);
std::vector<std::string> split (const std::string & str, const bool keepEmptys = 0,
const unsigned long limit = 0);
std::vector<std::string> findAll (const std::string & str);
bool matches (const std::string & str);
/**
Returns the flags used during compilation of this pattern
@return The flags used during compilation of this pattern
*/
unsigned long getFlags () const;
/**
Returns the regular expression this pattern represents
@return The regular expression this pattern represents
*/
std::string getPattern () const;
/**
Creates a matcher object using the specified string and this pattern.
@param str The string to match against
@return A new matcher using object using this pattern and the specified
string
*/
Matcher * createMatcher (const std::string & str);
void print();
};
class NFANode
{
friend class Matcher;
public:
NFANode * next;
NFANode();
virtual ~NFANode();
virtual void findAllNodes(std::map<NFANode*, bool> & soFar);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const = 0;
virtual void print(const int indent);
inline virtual bool isGroupHeadNode() const { return false; }
inline virtual bool isStartOfInputNode() const { return false; }
};
class NFACharNode : public NFANode
{
protected:
char ch;
public:
NFACharNode(const char c);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFACICharNode : public NFANode
{
protected:
char ch;
public:
NFACICharNode(const char c);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAStartNode : public NFANode
{
public:
NFAStartNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAEndNode : public NFANode
{
public:
NFAEndNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAQuantifierNode : public NFANode
{
public:
int min, max;
NFANode * inner;
virtual void findAllNodes(std::map<NFANode*, bool> & soFar);
NFAQuantifierNode(Pattern * pat, NFANode * internal,
const int minMatch = Pattern::MIN_QMATCH,
const int maxMatch = Pattern::MAX_QMATCH);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAGreedyQuantifierNode : public NFAQuantifierNode
{
public:
NFAGreedyQuantifierNode(Pattern * pat, NFANode * internal,
const int minMatch = Pattern::MIN_QMATCH,
const int maxMatch = Pattern::MAX_QMATCH);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual int matchInternal(const std::string & str, Matcher * matcher, const int curInd, const int soFar, const int depth) const;
};
class NFALazyQuantifierNode : public NFAQuantifierNode
{
public:
NFALazyQuantifierNode(Pattern * pat, NFANode * internal,
const int minMatch = Pattern::MIN_QMATCH,
const int maxMatch = Pattern::MAX_QMATCH);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAPossessiveQuantifierNode : public NFAQuantifierNode
{
public:
NFAPossessiveQuantifierNode(Pattern * pat, NFANode * internal,
const int minMatch = Pattern::MIN_QMATCH,
const int maxMatch = Pattern::MAX_QMATCH);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAAcceptNode : public NFANode
{
public:
NFAAcceptNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAClassNode : public NFANode
{
public:
bool inv;
std::map<char, bool> vals;
NFAClassNode(const bool invert = 0);
NFAClassNode(const std::string & clazz, const bool invert);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFACIClassNode : public NFANode
{
public:
bool inv;
std::map<char, bool> vals;
NFACIClassNode(const bool invert = 0);
NFACIClassNode(const std::string & clazz, const bool invert);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFASubStartNode : public NFANode
{
public:
NFASubStartNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAOrNode : public NFANode
{
public:
NFANode * one;
NFANode * two;
NFAOrNode(NFANode * first, NFANode * second);
virtual void findAllNodes(std::map<NFANode*, bool> & soFar);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAQuoteNode : public NFANode
{
public:
std::string qStr;
NFAQuoteNode(const std::string & quoted);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFACIQuoteNode : public NFANode
{
public:
std::string qStr;
NFACIQuoteNode(const std::string & quoted);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFALookAheadNode : public NFANode
{
public:
bool pos;
NFANode * inner;
NFALookAheadNode(NFANode * internal, const bool positive);
virtual void findAllNodes(std::map<NFANode*, bool> & soFar);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFALookBehindNode : public NFANode
{
public:
bool pos;
std::string mStr;
NFALookBehindNode(const std::string & str, const bool positive);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAStartOfLineNode : public NFANode
{
public:
NFAStartOfLineNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAEndOfLineNode : public NFANode
{
public:
NFAEndOfLineNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAReferenceNode : public NFANode
{
public:
int gi;
NFAReferenceNode(const int groupIndex);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAStartOfInputNode : public NFANode
{
public:
NFAStartOfInputNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
inline virtual bool isStartOfInputNode() const { return true; }
};
class NFAEndOfInputNode : public NFANode
{
public:
bool term;
NFAEndOfInputNode(const bool lookForTerm);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAWordBoundaryNode : public NFANode
{
public:
bool pos;
NFAWordBoundaryNode(const bool positive);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAEndOfMatchNode : public NFANode
{
public:
NFAEndOfMatchNode();
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
};
class NFAGroupHeadNode : public NFANode
{
public:
int gi;
NFAGroupHeadNode(const int groupIndex);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
inline virtual bool isGroupHeadNode() const { return true; }
virtual void print(const int indent);
};
class NFAGroupTailNode : public NFANode
{
public:
int gi;
NFAGroupTailNode(const int groupIndex);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAGroupLoopPrologueNode : public NFANode
{
public:
int gi;
NFAGroupLoopPrologueNode(const int groupIndex);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
class NFAGroupLoopNode : public NFANode
{
public:
int gi, min, max, type;
NFANode * inner;
NFAGroupLoopNode(NFANode * internal, const int minMatch,
const int maxMatch, const int groupIndex, const int matchType);
virtual void findAllNodes(std::map<NFANode*, bool> & soFar);
virtual int match(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
int matchGreedy(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
int matchLazy(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
int matchPossessive(const std::string & str, Matcher * matcher, const int curInd = 0, const int depth = 0) const;
virtual void print(const int indent);
};
#endif
src/regexp/WCMatcher.h
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
#ifndef __WCMATCHER_H__
#define __WCMATCHER_H__
#include <string>
#include <vector>
#include <regexp/WCPattern.h>
/**
A matcher is a non thread-safe object used to scan strings using a given
{@link WCPattern WCPattern} object. Using a <code>WCMatcher</code> is the preferred
method for scanning strings. WCMatchers are not thread-safe. WCMatchers require
very little dynamic memory, hence one is encouraged to create several
instances of a matcher when necessary as opposed to sharing a single instance
of a matcher.
<p>
The most common methods needed by the matcher are <code>matches</code>,
<code>findNextMatch</code>, and <code>getGroup</code>. <code>matches</code>
and <code>findNextMatch</code> both return success or failure, and further
details can be gathered from their documentation.
<p>
Unlike Java's <code>WCMatcher</code>, this class allows you to change the string
you are matching against. This provides a small optimization, since you no
longer need multiple matchers for a single pattern in a single thread.
<p>
This class also provides an extremely handy method for replacing text with
captured data via the <code>replaceWithGroups</code> method. A typical
invocation looks like:
<pre>
wchar_t buf[10000];
std::wstring str = "\\5 (user name \\1) uses \\7 for his/her shell and \\6 is their home directory";
FILE * fp = fopen("/etc/passwd", "r");
WCPattern::registerWCPattern("entry", "[^:]+");
WCPattern * p = WCPattern::compile("^({entry}):({entry}):({entry}):({entry}):({entry}):({entry}):({entry})$",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WCPattern::MULTILINE_MATCHING | WCPattern::UNIX_LINE_MODE);
WCMatcher * m = p->createWCMatcher("");
while (fgets(buf, 9999, fp))
{
&nbsp;&nbsp;m->setString(buf);
&nbsp;&nbsp;if (m->matches())
&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;printf("%s\n", m->replaceWithGroups(str).c_str());
&nbsp;&nbsp;}
}
fclose(fp);
</pre>
Calling any of the following functions before first calling
<code>matches</code>, <code>findFirstMatch</code>, or
<code>findNextMatch</code> results in undefined behavior and may cause your
program to crash.
<code>
<ul>
<li>replaceWithGroups</code>
<li>getStartingIndex</li>
<li>getEndingIndex</li>
<li>getGroup</li>
<li>getGroups</li>
</ul>
</code>
<p>
The function <code>findFirstMatch</code> will attempt to find the first match
in the input string. The same results can be obtained by first calling
<code>reset</code> followed by <code>findNextMatch</code>.
<p>
To eliminate the necessity of looping through a string to find all the
matching substrings, <code>findAll</code> was created. The function will find
all matching substrings and return them in a <code>vector</code>. If you need
to examine specific capture groups within the substrings, then this method
should not be used.
@author Jeffery Stuart
@since March 2003, Stable Since November 2004
@version 1.07.00
@memo Mutable object used on instances of a WCPattern class
*/
class WCMatcher
{
friend class NFAUNode;
friend class NFAStartUNode;
friend class NFAEndUNode;
friend class NFAGroupHeadUNode;
friend class NFAGroupLoopUNode;
friend class NFAGroupLoopPrologueUNode;
friend class NFAGroupTailUNode;
friend class NFALookBehindUNode;
friend class NFAStartOfLineUNode;
friend class NFAEndOfLineUNode;
friend class NFAEndOfMatchUNode;
friend class NFAReferenceUNode;
friend class WCPattern;
private:
/**
Creates a new matcher object against <code>text</code> using
<code>pattern</code>.
@param pattern The pattern with which to search
@param text The text in which to search
*/
WCMatcher(WCPattern * pattern, const std::wstring & text);
protected:
/// The pattern we use to match
WCPattern * pat;
/// The string in which we are matching
std::wstring str;
/// The starting point of our match
int start;
/// An array of the starting positions for each group
int * starts;
/// An array of the ending positions for each group
int * ends;
/// An array of private data used by NFAUNodes during matching
int * groups;
/// An array of private data used by NFAUNodes during matching
int * groupIndeces;
/// An array of private data used by NFAUNodes during matching
int * groupPos;
/// The ending index of the last match
int lm;
/// The number of capturing groups we have
int gc;
/// The number of non-capturing groups we havew
int ncgc;
/// Whether or not we have matched something (used only by findFirstMatch and findNextMatch)
int matchedSomething;
/// The flags with which we were made
unsigned long flags;
/// Called by reset to clear the group arrays
void clearGroups();
public:
/// Used internally by match to signify we want the entire string matched
const static int MATCH_ENTIRE_STRING;
public:
/// Cleans up the dynamic memory used by this matcher
~WCMatcher();
/**
Replaces the contents of <code>str</code> with the appropriate captured
text. <code>str</code> should have at least one back reference, otherwise
this function does nothing.
@param str The string in which to replace text
@return A string with all backreferences appropriately replaced
*/
std::wstring replaceWithGroups(const std::wstring & str);
/**
The flags currently being used by the matcher.
@return Zero
*/
unsigned long getFlags() const;
/**
The text being searched by the matcher.
@return the text being searched by the matcher.
*/
std::wstring getText() const;
/**
Scans the string from start to finish for a match. The entire string must
match for this function to return success. Group variables are
appropriately set and can be queried after this function returns.
@return Success if and only if the entire string matches the pattern
*/
bool matches();
/**
Scans the string for the first substring matching the pattern. The entire
string does not necessarily have to match for this function to return
success. Group variables are appropriately set and can be queried after
this function returns.
@return Success if any substring matches the specified pattern
*/
bool findFirstMatch();
/**
Scans the string for the next substring matching the pattern. If no calls
have been made to findFirstMatch of findNextMatch since the last call to
reset, matches, or setString, then this function's behavior results to
that of findFirstMatch.
@return Success if another substring can be found that matches the pattern
*/
bool findNextMatch();
/**
Returns a vector of every substring in order which matches the given
pattern.
@return Every substring in order which matches the given pattern
*/
std::vector<std::wstring> findAll();
/**
Resets the internal state of the matcher
*/
void reset();
/**
Same as getText. Left n for backwards compatibilty with old source code
@return Returns the string that is currently being used for matching
*/
inline std::wstring getString() const { return str; }
/**
Sets the string to scan
@param newStr The string to scan for subsequent matches
*/
inline void setString(const std::wstring & newStr) { str = newStr; reset(); }
/**
Returns the starting index of the specified group.
@param groupNum The group to query
@return The starting index of the group if it was matched, -1 for an
invalid group or if the group was not matched
*/
int getStartingIndex(const int groupNum = 0) const;
/**
Returns the ending index of the specified group.
@param groupNum The group to query
@return The ending index of the group if it was matched, -1 for an
invalid group or if the group was not matched
*/
int getEndingIndex(const int groupNum = 0) const;
/**
Returns the specified group. An empty string ("") does not necessarily
mean the group was not matched. A group such as (a*b?) could be matched by
a zero length. If an empty string is returned, getStartingIndex can be
called to determine if the group was actually matched.
@param groupNum The group to query
@return The text of the group
*/
std::wstring getGroup(const int groupNum = 0) const;
/**
Returns every capture group in a vector
@param includeGroupZero Whether or not include capture group zero
@return Every capture group
*/
std::vector<std::wstring> getGroups(const bool includeGroupZero = 0) const;
};
#endif
src/regexp/WCPattern.h
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
#ifndef __WCPATTERN_H__
#define __WCPATTERN_H__
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
#include <vector>
#include <string>
#include <map>
class WCMatcher;
class NFAUNode;
class NFAQuantifierUNode;
namespace std
{
typedef std::basic_string<wchar_t> wstring;
}
/**
This pattern class is very similar in functionality to Java's
java.util.regex.WCPattern class. The pattern class represents an immutable
regular expression object. Instead of having a single object contain both the
regular expression object and the matching object, instead the two objects are
split apart. The {@link WCMatcher WCMatcher} class represents the maching
object.
The WCPattern class works primarily off of "compiled" patterns. A typical
instantiation of a regular expression looks like:
<pre>
WCPattern * p = WCPattern::compile(L"a*b");
WCMatcher * m = p->createWCMatcher(L"aaaaaab");
if (m->matches()) ...
</pre>
However, if you do not need to use a pattern more than once, it is often times
okay to use the WCPattern's static methods insteads. An example looks like this:
<pre>
if (WCPattern::matches(L"a*b", L"aaaab")) { ... }
</pre>
This class does not currently support unicode. The unicode update for this
class is coming soon.
This class is partially immutable. It is completely safe to call createWCMatcher
concurrently in different threads, but the other functions (e.g. split) should
not be called concurrently on the same <code>WCPattern</code>.
<table border="0" cellpadding="1" cellspacing="0">
<tr align="left" bgcolor="#CCCCFF">
<td>
<b>Construct</b>
</td>
<td>
<b>Matches</b>
</th>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Characters</b>
</td>
</tr>
<tr>
<td>
<code><i>x</i></code>
</td>
<td>
The character <code><i>x</i></code>
</td>
</tr>
<tr>
<td>
<code>\\</code>
</td>
<td>
The character <code>\</code>
</td>
</tr>
<tr>
<td>
<code>\0<i>nn</i></code>
</td>
<td>
The character with octal ASCII value <code><i>nn</i></code>
</td>
</tr>
<tr>
<td>
<code>\0<i>nnn</i></code>
</td>
<td>
The character with octal ASCII value <code><i>nnn</i></code>
</td>
</tr>
<tr>
<td>
<code>\x<i>hh</i></code>
</td>
<td>
The character with hexadecimal ASCII value <code><i>hh</i></code>
</td>
</tr>
<tr>
<td>
<code>\t</code>
</td>
<td>
A tab character
</td>
</tr>
<tr>
<td>
<code>\r</code>
</td>
<td>
A carriage return character
</td>
</tr>
<tr>
<td>
<code>\n</code>
</td>
<td>
A new-line character
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td>
<b>Character Classes</b>
</td>
</tr>
<tr>
<td>
<code>[abc]</code>
</td>
<td>
Either <code>a</code>, <code>b</code>, or <code>c</code>
</td>
</tr>
<tr>
<td>
<code>[^abc]</code>
</td>
<td>
Any character but <code>a</code>, <code>b</code>, or <code>c</code>
</td>
</tr>
<tr>
<td>
<code>[a-zA-Z]</code>
</td>
<td>
Any character ranging from <code>a</code> thru <code>z</code>, or
<code>A</code> thru <code>Z</code>
</td>
</tr>
<tr>
<td>
<code>[^a-zA-Z]</code>
</td>
<td>
Any character except those ranging from <code>a</code> thru
<code>z</code>, or <code>A</code> thru <code>Z</code>
</td>
</tr>
<tr>
<td>
<code>[a\-z]</code>
</td>
<td>
Either <code>a</code>, <code>-</code>, or <code>z</code>
</td>
</tr>
<tr>
<td>
<code>[a-z[A-Z]]</code>
</td>
<td>
Same as <code>[a-zA-Z]</code>
</td>
</tr>
<tr>
<td>
<code>[a-z&&[g-i]]</code>
</td>
<td>
Any character in the intersection of <code>a-z</code> and
<code>g-i</code>
</td>
</tr>
<tr>
<td>
<code>[a-z&&[^g-i]]</code>
</td>
<td>
Any character in <code>a-z</code> and not in <code>g-i</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Prefefined character classes</b>
</td>
</tr>
<tr>
<td>
<code><b>.</b></code>
</td>
<td>
Any character. Multiline matching must be compiled into the pattern for
<code><b>.</b></code> to match a <code>\r</code> or a <code>\n</code>.
Even if multiline matching is enabled, <code><b>.</b></code> will not
match a <code>\r\n</code>, only a <code>\r</code> or a <code>\n</code>.
</td>
</tr>
<tr>
<td>
<code>\d</code>
</td>
<td>
<code>[0-9]</code>
</td>
</tr>
<tr>
<td>
<code>\D</code>
</td>
<td>
<code>[^\d]</code>
</td>
</tr>
<tr>
<td>
<code>\s</code>
</td>
<td>
<code>[&nbsp;\t\r\n\x0B]</code>
</td>
</tr>
<tr>
<td>
<code>\S</code>
</td>
<td>
<code>[^\s]</code>
</td>
</tr>
<tr>
<td>
<code>\w</code>
</td>
<td>
<code>[a-zA-Z0-9_]</code>
</td>
</tr>
<tr>
<td>
<code>\W</code>
</td>
<td>
<code>[^\w]</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>POSIX character classes
</td>
</tr>
<tr>
<td>
<code>\p{Lower}</code>
</td>
<td>
<code>[a-z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Upper}</code>
</td>
<td>
<code>[A-Z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{ASCII}</code>
</td>
<td>
<code>[\x00-\x7F]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Alpha}</code>
</td>
<td>
<code>[a-zA-Z]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Digit}</code>
</td>
<td>
<code>[0-9]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Alnum}</code>
</td>
<td>
<code>[\w&&[^_]]</code>
</td>
</tr>
<tr>
<td>
<code>\p{Punct}</code>
</td>
<td>
<code>[!"#$%&'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~]</code>
</td>
</tr>
<tr>
<td>
<code>\p{XDigit}</code>
</td>
<td>
<code>[a-fA-F0-9]</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Boundary Matches</b>
</td>
</tr>
<tr>
<td>
<code>^</code>
</td>
<td>
The beginning of a line. Also matches the beginning of input.
</td>
</tr>
<tr>
<td>
<code>$</code>
</td>
<td>
The end of a line. Also matches the end of input.
</td>
</tr>
<tr>
<td>
<code>\b</code>
</td>
<td>
A word boundary
</td>
</tr>
<tr>
<td>
<code>\B</code>
</td>
<td>
A non word boundary
</td>
</tr>
<tr>
<td>
<code>\A</code>
</td>
<td>
The beginning of input
</td>
</tr>
<tr>
<td>
<code>\G</code>
</td>
<td>
The end of the previous match. Ensures that a "next" match will only
happen if it begins with the character immediately following the end of
the "current" match.
</td>
</tr>
<tr>
<td>
<code>\Z</code>
</td>
<td>
The end of input. Will also match if there is a single trailing
<code>\r\n</code>, a single trailing <code>\r</code>, or a single
trailing <code>\n</code>.
</td>
</tr>
<tr>
<td>
<code>\z</code>
</td>
<td>
The end of input
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Greedy Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x?</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x+</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Possessive Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x?+</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*+</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x++</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}+</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}+</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}+</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}+</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Reluctant Quantifiers</b>
</td>
</tr>
<tr>
<td>
<code><i>x??</i></code>
</td>
<td>
<i>x</i>, either zero times or one time
</td>
</tr>
<tr>
<td>
<code><i>x*?</i></code>
</td>
<td>
<i>x</i>, zero or more times
</td>
</tr>
<tr>
<td>
<code><i>x+?</i></code>
</td>
<td>
<i>x</i>, one or more times
</td>
</tr>
<tr>
<td>
<code><i>x{n}?</i></code>
</td>
<td>
<i>x</i>, exactly n times
</td>
</tr>
<tr>
<td>
<code><i>x{n,}?</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{,m}?</i></code>
</td>
<td>
<i>x</i>, at most <code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
<code><i>x{n,m}?</i></code>
</td>
<td>
<i>x</i>, at least <code><i>n</i></code> times and at most
<code><i>m</i></code> times
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Operators</b>
</td>
</tr>
<tr>
<td>
<code><i>xy</i></code>
</td>
<td>
<code><i>x</i></code> then <code><i>y</i></code>
</td>
</tr>
<tr>
<td>
<code><i>x</i></code>|<code><i>y</i></code>
</td>
<td>
<code><i>x</i></code> or <code><i>y</i></code>
</td>
</tr>
<tr>
<td>
<code>(<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code> as a capturing group
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Quoting</b>
</td>
</tr>
<tr>
<td>
<code>\Q</code>
</td>
<td>
Nothing, but treat every character (including \s) literally until a
matching <code>\E</code>
</td>
</tr>
<tr>
<td>
<code>\E</code>
</td>
<td>
Nothing, but ends its matching <code>\Q</code>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Special Constructs</b>
</td>
</tr>
<tr>
<td>
<code>(?:<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, but not as a capturing group
</td>
</tr>
<tr>
<td>
<code>(?=<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via positive lookahead. This means that the
expression will match only if it is trailed by <code><i>x</i></code>.
It will not "eat" any of the characters matched by
<code><i>x</i></code>.
</td>
</tr>
<tr>
<td>
<code>(?!<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via negative lookahead. This means that the
expression will match only if it is not trailed by
<code><i>x</i></code>. It will not "eat" any of the characters
matched by <code><i>x</i></code>.
</td>
</tr>
<tr>
<td>
<code>(?<=<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via positive lookbehind. <code><i>x</i></code>
cannot contain any quantifiers.
</td>
</tr>
<tr>
<td>
<code>(?<!<i>x</i>)</code>
</td>
<td>
<code><i>x</i></code>, via negative lookbehind. <code><i>x</i></code>
cannot contain any quantifiers.
</td>
</tr>
<tr>
<td>
<code>(?><i>x</i>)</code>
</td>
<td>
<code><i>x</i>{1}+</code>
</td>
</tr>
<tr>
<td colspan="2">
&nbsp;
</td>
</tr>
<tr>
<td colspan="2">
<b>Registered Expression Matching</b>
</td>
</tr>
<tr>
<td>
<code>{<i>x</i>}</code>
</td>
<td>
The registered pattern <code><i>x</i></code>
</td>
</tr>
</table>
<hr>
<i>Begin Text Extracted And Modified From java.util.regex.WCPattern documentation</i>
<h4> Backslashes, escapes, and quoting </h4>
<p> The backslash character (<tt>(wchar_t)'\'</tt>) serves to introduce escaped
constructs, as defined in the table above, as well as to quote characters
that otherwise would be interpreted as unescaped constructs. Thus the
expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
left brace.
<p> It is an error to use a backslash prior to any alphabetic character that
does not denote an escaped construct; these are reserved for future
extensions to the regular-expression language. A backslash may be used
prior to a non-alphabetic character regardless of whether that character is
part of an unescaped construct.
<p>It is necessary to double backslashes in string literals that represent
regular expressions to protect them from interpretation by a compiler. The
string literal <tt>"&#92;b"</tt>, for example, matches a single backspace
character when interpreted as a regular expression, while
<tt>"&#92;&#92;b"</tt> matches a word boundary. The string litera
<tt>"&#92;(hello&#92;)"</tt> is illegal and leads to a compile-time error;
in order to match the string <tt>(hello)</tt> the string literal
<tt>"&#92;&#92;(hello&#92;&#92;)"</tt> must be used.
<h4> Character Classes </h4>
<p> Character classes may appear within other character classes, and
may be composed by the union operator (implicit) and the intersection
operator (<tt>&amp;&amp;</tt>).
The union operator denotes a class that contains every character that is
in at least one of its operand classes. The intersection operator
denotes a class that contains every character that is in both of its
operand classes.
<p> The precedence of character-class operators is as follows, from
highest to lowest:
<blockquote><table border="0" cellpadding="1" cellspacing="0"
summary="Precedence of character class operators.">
<tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><tt>\x</tt></td></tr>
<tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Range</td>
<td><tt>a-z</tt></td></tr>
<tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Grouping</td>
<td><tt>[...]</tt></td></tr>
<tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Intersection</td>
<td><tt>[a-z&&[aeiou]]</tt></td></tr>
<tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td>Union</td>
<td><tt>[a-e][i-u]<tt></td></tr>
</table></blockquote>
<p> Note that a different set of metacharacters are in effect inside
a character class than outside a character class. For instance, the
regular expression <tt>.</tt> loses its special meaning inside a
character class, while the expression <tt>-</tt> becomes a range
forming metacharacter.
<a name="lt">
<a name="cg">
<h4> Groups and capturing </h4>
<p> Capturing groups are numbered by counting their opening parentheses from
left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
are four such groups: </p>
<blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
<tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>((A)(B(C)))</tt></td></tr>
<tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(A)</tt></td></tr>
<tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(B(C))</tt></td></tr>
<tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
<td><tt>(C)</tt></td></tr>
</table></blockquote>
<p> Group zero always stands for the entire expression.
<p> Capturing groups are so named because, during a match, each subsequence
of the input sequence that matches such a group is saved. The captured
subsequence may be used later in the expression, via a back reference, and
may also be retrieved from the matcher once the match operation is complete.
<p> The captured input associated with a group is always the subsequence
that the group most recently matched. If a group is evaluated a second time
because of quantification then its previously-captured value, if any, will
be retained if the second evaluation fails. Matching the string
<tt>L"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
group two set to <tt>L"b"</tt>. All captured input is discarded at the
beginning of each match.
<p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups
that do not capture text and do not count towards the group total.
<h4> WC support </h4>
<p> Coming Soon.
<h4> Comparison to Perl 5 </h4>
<p>The <code>WCPattern</code> engine performs traditional NFA-based matching
with ordered alternation as occurs in Perl 5.
<p> Perl constructs not supported by this class: </p>
<ul>
<li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and
<tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
</p></li>
<li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
<li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
<li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
<tt>\L</tt>, and <tt>\U</tt>. </p></li>
<li><p> Embedded flags</p></li>
</ul>
<p> Constructs supported by this class but not by Perl: </p>
<ul>
<li><p> Possessive quantifiers, which greedily match as much as they can
and do not back off, even when doing so would allow the overall match to
succeed. </p></li>
<li><p> Character-class union and intersection as described
above.</p></li>
</ul>
<p> Notable differences from Perl: </p>
<ul>
<li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
as back references; a backslash-escaped number greater than <tt>9</tt> is
treated as a back reference if at least that many subexpressions exist,
otherwise it is interpreted, if possible, as an octal escape. In this
class octal escapes must always begin with a zero. In this class,
<tt>\1</tt> through <tt>\9</tt> are always interpreted as back
references, and a larger number is accepted as a back reference if at
least that many subexpressions exist at that point in the regular
expression, otherwise the parser will drop digits until the number is
smaller or equal to the existing number of groups or it is one digit.
</p></li>
<li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
where the last match left off. This functionality is provided implicitly
by the <CODE>WCMatcher</CODE> class: Repeated invocations of the
<code>find</code> method will resume where the last match left off,
unless the matcher is reset. </p></li>
<li><p> Perl is forgiving about malformed matching constructs, as in the
expression <tt>*a</tt>, as well as dangling brackets, as in the
expression <tt>abc]</tt>, and treats them as literals. This
class also strict and will not compile a pattern when dangling characters
are encountered.</p></li>
</ul>
<p> For a more precise description of the behavior of regular expression
constructs, please see <a href="http://www.oreilly.com/catalog/regex2/">
<i>Mastering Regular Expressions, 2nd Edition</i>, Jeffrey E. F. Friedl,
O'Reilly and Associates, 2002.</a>
</p>
<P>
<i>End Text Extracted And Modified From java.util.regex.WCPattern documentation</i>
<hr>
@author Jeffery Stuart
@since November 24th, 2007
@version 1.08.00
@memo A class used to represent "PERL 5"-ish regular expressions
*/
class WCPattern
{
friend class WCMatcher;
friend class NFAUNode;
friend class NFAQuantifierUNode;
private:
/**
This constructor should not be called directly. Those wishing to use the
WCPattern class should instead use the {@link compile compile} method.
@param rhs The pattern to compile
@memo Creates a new pattern from the regular expression in <code>rhs</code>.
*/
WCPattern(const std::wstring & rhs);
protected:
/**
This currently is not used, so don't try to do anything with it.
@memo Holds all the compiled patterns for quick access.
*/
static std::map<std::wstring, WCPattern *> compiledWCPatterns;
/**
Holds all of the registered patterns as strings. Due to certain problems
with compilation of patterns, especially with capturing groups, this seemed
to be the best way to do it.
*/
static std::map<std::wstring, std::pair<std::wstring, unsigned long> > registeredWCPatterns;
protected:
/**
Holds all the NFA nodes used. This makes deletion of a pattern, as well as
clean-up from an unsuccessful compile much easier and faster.
*/
std::map<NFAUNode*, bool> nodes;
/**
Used when methods like split are called. The matcher class uses a lot of
dynamic memeory, so having an instance increases speedup of certain
operations.
*/
WCMatcher * matcher;
/**
The front node of the NFA.
*/
NFAUNode * head;
/**
The actual regular expression we rerpesent
*/
std::wstring pattern;
/**
Flag used during compilation. Once the pattern is successfully compiled,
<code>error</code> is no longer used.
*/
bool error;
/**
Used during compilation to keep track of the current index into
<code>{@link pattern pattern}<code>. Once the pattern is successfully
compiled, <code>error</code> is no longer used.
*/
int curInd;
/**
The number of capture groups this contains.
*/
int groupCount;
/**
The number of non-capture groups this contains.
*/
int nonCapGroupCount;
/**
The flags specified when this was compiled.
*/
unsigned long flags;
protected:
/**
Raises an error during compilation. Compilation will cease at that point
and compile will return <code>NULL</code>.
*/
void raiseError();
/**
Convenience function for registering a node in <code>nodes</code>.
@param node The node to register
@return The registered node
*/
NFAUNode * registerNode(NFAUNode * node);
/**
Calculates the union of two strings. This function will first sort the
strings and then use a simple selection algorithm to find the union.
@param s1 The first "class" to union
@param s2 The second "class" to union
@return A new string containing all unique characters. Each character
must have appeared in one or both of <code>s1</code> and
<code>s2</code>.
*/
std::wstring classUnion (std::wstring s1, std::wstring s2) const;
/**
Calculates the intersection of two strings. This function will first sort
the strings and then use a simple selection algorithm to find the
intersection.
@param s1 The first "class" to intersect
@param s2 The second "class" to intersect
@return A new string containing all unique characters. Each character
must have appeared both <code>s1</code> and <code>s2</code>.
*/
std::wstring classIntersect (std::wstring s1, std::wstring s2) const;
/**
Calculates the negation of a string. The negation is the set of all
characters between <code>\x00</code> and <code>\xFF</code> not
contained in <code>s1</code>.
@param s1 The "class" to be negated.
@param s2 The second "class" to intersect
@return A new string containing all unique characters. Each character
must have appeared both <code>s1</code> and <code>s2</code>.
*/
std::wstring classNegate (std::wstring s1) const;
/**
Creates a new "class" representing the range from <code>low</code> thru
<code>hi</code>. This function will wrap if <code>low</code> &gt;
<code>hi</code>. This is a feature, not a buf. Sometimes it is useful
to be able to say [\x70-\x10] instead of [\x70-\x7F\x00-\x10].
@param low The beginning character
@param hi The ending character
@return A new string containing all the characters from low thru hi.
*/
std::wstring classCreateRange(wchar_t low, wchar_t hi) const;
/**
Extracts a decimal number from the substring of member-variable
<code>{@link pattern pattern}<code> starting at <code>start</code> and
ending at <code>end</code>.
@param start The starting index in <code>{@link pattern pattern}<code>
@param end The last index in <code>{@link pattern pattern}<code>
@return The decimal number in <code>{@link pattern pattern}<code>
*/
int getInt(int start, int end);
/**
Parses a <code>{n,m}</code> string out of the member-variable
<code>{@link pattern pattern}<code> stores the result in <code>sNum</code>
and <code>eNum</code>.
@param sNum Output parameter. The minimum number of matches required
by the curly quantifier are stored here.
@param eNum Output parameter. The maximum number of matches allowed
by the curly quantifier are stored here.
@return Success/Failure. Fails when the curly does not have the proper
syntax
*/
bool quantifyCurly(int & sNum, int & eNum);
/**
Tries to quantify the currently parsed group. If the group being parsed
is indeed quantified in the member-variable
<code>{@link pattern pattern}<code>, then the NFA is modified accordingly.
@param start The starting node of the current group being parsed
@param stop The ending node of the current group being parsed
@param gn The group number of the current group being parsed
@return The node representing the starting node of the group. If the
group becomes quantified, then this node is not necessarily
a GroupHead node.
*/
NFAUNode * quantifyGroup(NFAUNode * start, NFAUNode * stop, const int gn);
/**
Tries to quantify the last parsed expression. If the character was indeed
quantified, then the NFA is modified accordingly.
@param newNode The recently created expression node
@return The node representing the last parsed expression. If the
expression was quantified, <code>return value != newNode</code>
*/
NFAUNode * quantify(NFAUNode * newNode);
/**
Parses the current class being examined in
<code>{@link pattern pattern}</code>.
@return A string of unique characters contained in the current class being
parsed
*/
std::wstring parseClass();
/**
Parses the current POSIX class being examined in
<code>{@link pattern pattern}</code>.
@return A string of unique characters representing the POSIX class being
parsed
*/
std::wstring parsePosix();
/**
Returns a string containing the octal character being parsed
@return The string contained the octal value being parsed
*/
std::wstring parseOctal();
/**
Returns a string containing the hex character being parsed
@return The string contained the hex value being parsed
*/
std::wstring parseHex();
/**
Returns a new node representing the back reference being parsed
@return The new node representing the back reference being parsed
*/
NFAUNode * parseBackref();
/**
Parses the escape sequence currently being examined. Determines if the
escape sequence is a class, a single character, or the beginning of a
quotation sequence.
@param inv Output parameter. Whether or not to invert the returned class
@param quo Output parameter. Whether or not this sequence starts a
quotation.
@return The characters represented by the class
*/
std::wstring parseEscape(bool & inv, bool & quo);
/**
Parses a supposed registered pattern currently under compilation. If the
sequence of characters does point to a registered pattern, then the
registered pattern is appended to <code>*end<code>. The registered pattern
is parsed with the current compilation flags.
@param end The ending node of the thus-far compiled pattern
@return The new end node of the current pattern
*/
NFAUNode * parseRegisteredWCPattern(NFAUNode ** end);
/**
Parses a lookbehind expression. Appends the necessary nodes
<code>*end</code>.
@param pos Positive or negative look behind
@param end The ending node of the current pattern
@return The new end node of the current pattern
*/
NFAUNode * parseBehind(const bool pos, NFAUNode ** end);
/**
Parses the current expression and tacks on nodes until a \E is found.
@return The end of the current pattern
*/
NFAUNode * parseQuote();
/**
Parses <code>{@link pattern pattern}</code>. This function is called
recursively when an or (<code>|</code>) or a group is encountered.
@param inParen Are we currently parsing inside a group
@param inOr Are we currently parsing one side of an or (<code>|</code>)
@param end The end of the current expression
@return The starting node of the NFA constructed from this parse
*/
NFAUNode * parse(const bool inParen = 0, const bool inOr = 0, NFAUNode ** end = NULL);
public:
/// We should match regardless of case
const static unsigned long CASE_INSENSITIVE;
/// We are implicitly quoted
const static unsigned long LITERAL;
/// @memo We should treat a <code><b>.</b></code> as [\x00-\x7F]
const static unsigned long DOT_MATCHES_ALL;
/** <code>^</code> and <code>$</code> should anchor to the beginning and
ending of lines, not all input
*/
const static unsigned long MULTILINE_MATCHING;
/** When enabled, only instances of <code>\n</codes> are recognized as
line terminators
*/
const static unsigned long UNIX_LINE_MODE;
/// The absolute minimum number of matches a quantifier can match (0)
const static int MIN_QMATCH;
/// The absolute maximum number of matches a quantifier can match (0x7FFFFFFF)
const static int MAX_QMATCH;
public:
/**
Call this function to compile a regular expression into a
<code>WCPattern</code> object. Special values can be assigned to
<code>mode</code> when certain non-standard behaviors are expected from
the <code>WCPattern</code> object.
@param pattern The regular expression to compile
@param mode A bitwise or of flags signalling what special behaviors are
wanted from this <code>WCPattern</code> object
@return If successful, <code>compile</code> returns a <code>WCPattern</code>
pointer. Upon failure, <code>compile</code> returns
<code>NULL</code>
*/
static WCPattern * compile (const std::wstring & pattern,
const unsigned long mode = 0);
/**
Dont use this function. This function will compile a pattern, and cache
the result. This will eventually be used as an optimization when people
just want to call static methods using the same pattern over and over
instead of first compiling the pattern and then using the compiled
instance for matching.
@param pattern The regular expression to compile
@param mode A bitwise or of flags signalling what special behaviors are
wanted from this <code>WCPattern</code> object
@return If successful, <code>compileAndKeep</code> returns a
<code>WCPattern</code> pointer. Upon failure, <code>compile</code>
returns <code>NULL</code>.
*/
static WCPattern * compileAndKeep (const std::wstring & pattern,
const unsigned long mode = 0);
/**
Searches through <code>replace</code> and replaces all substrings matched
by <code>pattern</code> with <code>str</code>. <code>str</code> may
contain backreferences (e.g. <code>\1</code>) to capture groups. A typical
invocation looks like:
<p>
<code>
WCPattern::replace(L"(a+)b(c+)", L"abcccbbabcbabc", L"\\2b\\1");
</code>
<p>
which would replace <code>abcccbbabcbabc</code> with
<code>cccbabbcbabcba</code>.
@param pattern The regular expression
@param str The replacement text
@param replacementText The string in which to perform replacements
@param mode The special mode requested of the <code>WCPattern</code>
during the replacement process
@return The text with the replacement string substituted where necessary
*/
static std::wstring replace (const std::wstring & pattern,
const std::wstring & str,
const std::wstring & replacementText,
const unsigned long mode = 0);
/**
Splits the specified string over occurrences of the specified pattern.
Empty strings can be optionally ignored. The number of strings returned is
configurable. A typical invocation looks like:
<p>
<code>
std::wstring str(strSize, 0);<br>
FILE * fp = fopen(fileName, "r");<br>
fread((char*)str.data(), strSize * 2, 1, fp);<br>
fclose(fp);<br>
<br>
std::vector&lt;std::wstring&gt; lines = WCPattern::split(L"[\r\n]+", str, true);<br>
<br>
</code>
@param pattern The regular expression
@param replace The string to split
@param keepEmptys Whether or not to keep empty strings
@param limit The maximum number of splits to make
@param mode The special mode requested of the <code>WCPattern</code>
during the split process
@return All substrings of <code>str</code> split across <code>pattern</code>.
*/
static std::vector<std::wstring> split (const std::wstring & pattern,
const std::wstring & str,
const bool keepEmptys = 0,
const unsigned long limit = 0,
const unsigned long mode = 0);
/**
Finds all the instances of the specified pattern within the string. You
should be careful to only pass patterns with a minimum length of one. For
example, the pattern <code>a*</code> can be matched by an empty string, so
instead you should pass <code>a+</code> since at least one character must
be matched. A typical invocation of <code>findAll</code> looks like:
<p>
<code>
std::vector&lt;td::string&gt; numbers = WCPattern::findAll(L"\\d+", string);
</code>
<p>
@param pattern The pattern for which to search
@param str The string to search
@param mode The special mode requested of the <code>WCPattern</code>
during the find process
@return All instances of <code>pattern</code> in <code>str</code>
*/
static std::vector<std::wstring> findAll (const std::wstring & pattern,
const std::wstring & str,
const unsigned long mode = 0);
/**
Determines if an entire string matches the specified pattern
@param pattern The pattern for to match
@param str The string to match
@param mode The special mode requested of the <code>WCPattern</code>
during the replacement process
@return True if <code>str</code> is recognized by <code>pattern</code>
*/
static bool matches (const std::wstring & pattern,
const std::wstring & str,
const unsigned long mode = 0);
/**
Registers a pattern under a specific name for use in later compilations.
A typical invocation and later use looks like:
<p>
<code>
WCPattern::registerWCPattern(L"ip", L"(?:\\d{1,3}\\.){3}\\d{1,3}");<br>
WCPattern * p1 = WCPattern::compile(L"{ip}:\\d+");<br>
WCPattern * p2 = WCPattern::compile(L"Connection from ({ip}) on port \\d+");<br>
</code>
<p>
Multiple calls to <code>registerWCPattern</code> with the same
<code>name</code> will result in the pattern getting overwritten.
@param name The name to give to the pattern
@param pattern The pattern to register
@param mode Any special flags to use when compiling pattern
@return Success/Failure. Fails only if <code>pattern</code> has invalid
syntax
*/
static bool registerWCPattern(const std::wstring & name,
const std::wstring & pattern,
const unsigned long mode = 0);
/**
Clears the pattern registry
*/
static void unregisterWCPatterns();
/**
Don't use
*/
static void clearWCPatternCache();
/**
Searches through a string for the <code>n<sup>th</sup></code> match of the
given pattern in the string. Match indeces start at zero, not one.
A typical invocation looks like this:
<p>
<code>
std::pair&lt;std::wstring, int&gt; match = WCPattern::findNthMatch(L"\\d{1,3}", L"192.168.1.101:22", 1);<br>
wprintf(L"%s %i\n", match.first.c_str(), match.second);<br>
<br>
Output: 168 4<br>
<br>
@param pattern The pattern for which to search
@param str The string to search
@param matchNum Which match to find
@param mode Any special flags to use during the matching process
@return A string and an integer. The string is the string matched. The
integer is the starting location of the matched string in
<code>str</code>. You can check for success/failure by making sure
that the integer returned is greater than or equal to zero.
*/
static std::pair<std::wstring, int> findNthMatch (const std::wstring & pattern,
const std::wstring & str,
const int matchNum,
const unsigned long mode = 0);
public:
/**
Deletes all NFA nodes allocated during compilation
*/
~WCPattern();
std::wstring replace (const std::wstring & str,
const std::wstring & replacementText);
std::vector<std::wstring> split (const std::wstring & str, const bool keepEmptys = 0,
const unsigned long limit = 0);
std::vector<std::wstring> findAll (const std::wstring & str);
bool matches (const std::wstring & str);
/**
Returns the flags used during compilation of this pattern
@return The flags used during compilation of this pattern
*/
unsigned long getFlags () const;
/**
Returns the regular expression this pattern represents
@return The regular expression this pattern represents
*/
std::wstring getWCPattern () const;
/**
Creates a matcher object using the specified string and this pattern.
@param str The string to match against
@return A new matcher using object using this pattern and the specified
string
*/
WCMatcher * createWCMatcher (const std::wstring & str);
};
class NFAUNode
{
friend class WCMatcher;
public:
NFAUNode * next;
NFAUNode();
virtual ~NFAUNode();
virtual void findAllNodes(std::map<NFAUNode*, bool> & soFar);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const = 0;
inline virtual bool isGroupHeadNode() const { return false; }
inline virtual bool isStartOfInputNode() const { return false; }
};
class NFACharUNode : public NFAUNode
{
protected:
wchar_t ch;
public:
NFACharUNode(const wchar_t c);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFACICharUNode : public NFAUNode
{
protected:
wchar_t ch;
public:
NFACICharUNode(const wchar_t c);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAStartUNode : public NFAUNode
{
public:
NFAStartUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAEndUNode : public NFAUNode
{
public:
NFAEndUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAQuantifierUNode : public NFAUNode
{
public:
int min, max;
NFAUNode * inner;
virtual void findAllNodes(std::map<NFAUNode*, bool> & soFar);
NFAQuantifierUNode(WCPattern * pat, NFAUNode * internal,
const int minMatch = WCPattern::MIN_QMATCH,
const int maxMatch = WCPattern::MAX_QMATCH);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAGreedyQuantifierUNode : public NFAQuantifierUNode
{
public:
NFAGreedyQuantifierUNode(WCPattern * pat, NFAUNode * internal,
const int minMatch = WCPattern::MIN_QMATCH,
const int maxMatch = WCPattern::MAX_QMATCH);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
virtual int matchInternal(const std::wstring & str, WCMatcher * matcher, const int curInd, const int soFar) const;
};
class NFALazyQuantifierUNode : public NFAQuantifierUNode
{
public:
NFALazyQuantifierUNode(WCPattern * pat, NFAUNode * internal,
const int minMatch = WCPattern::MIN_QMATCH,
const int maxMatch = WCPattern::MAX_QMATCH);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAPossessiveQuantifierUNode : public NFAQuantifierUNode
{
public:
NFAPossessiveQuantifierUNode(WCPattern * pat, NFAUNode * internal,
const int minMatch = WCPattern::MIN_QMATCH,
const int maxMatch = WCPattern::MAX_QMATCH);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAAcceptUNode : public NFAUNode
{
public:
NFAAcceptUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAClassUNode : public NFAUNode
{
public:
bool inv;
std::map<wchar_t, bool> vals;
NFAClassUNode(const bool invert = 0);
NFAClassUNode(const std::wstring & clazz, const bool invert);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFACIClassUNode : public NFAUNode
{
public:
bool inv;
std::map<wchar_t, bool> vals;
NFACIClassUNode(const bool invert = 0);
NFACIClassUNode(const std::wstring & clazz, const bool invert);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFASubStartUNode : public NFAUNode
{
public:
NFASubStartUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAOrUNode : public NFAUNode
{
public:
NFAUNode * one;
NFAUNode * two;
NFAOrUNode(NFAUNode * first, NFAUNode * second);
virtual void findAllNodes(std::map<NFAUNode*, bool> & soFar);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAQuoteUNode : public NFAUNode
{
public:
std::wstring qStr;
NFAQuoteUNode(const std::wstring & quoted);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFACIQuoteUNode : public NFAUNode
{
public:
std::wstring qStr;
NFACIQuoteUNode(const std::wstring & quoted);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFALookAheadUNode : public NFAUNode
{
public:
bool pos;
NFAUNode * inner;
NFALookAheadUNode(NFAUNode * internal, const bool positive);
virtual void findAllNodes(std::map<NFAUNode*, bool> & soFar);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFALookBehindUNode : public NFAUNode
{
public:
bool pos;
std::wstring mStr;
NFALookBehindUNode(const std::wstring & str, const bool positive);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAStartOfLineUNode : public NFAUNode
{
public:
NFAStartOfLineUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAEndOfLineUNode : public NFAUNode
{
public:
NFAEndOfLineUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAReferenceUNode : public NFAUNode
{
public:
int gi;
NFAReferenceUNode(const int groupIndex);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAStartOfInputUNode : public NFAUNode
{
public:
NFAStartOfInputUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
inline virtual bool isStartOfInputNode() const { return false; }
};
class NFAEndOfInputUNode : public NFAUNode
{
public:
bool term;
NFAEndOfInputUNode(const bool lookForTerm);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAWordBoundaryUNode : public NFAUNode
{
public:
bool pos;
NFAWordBoundaryUNode(const bool positive);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAEndOfMatchUNode : public NFAUNode
{
public:
NFAEndOfMatchUNode();
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAGroupHeadUNode : public NFAUNode
{
public:
int gi;
NFAGroupHeadUNode(const int groupIndex);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
inline virtual bool isGroupHeadNode() const { return false; }
};
class NFAGroupTailUNode : public NFAUNode
{
public:
int gi;
NFAGroupTailUNode(const int groupIndex);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAGroupLoopPrologueUNode : public NFAUNode
{
public:
int gi;
NFAGroupLoopPrologueUNode(const int groupIndex);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
class NFAGroupLoopUNode : public NFAUNode
{
public:
int gi, min, max, type;
NFAUNode * inner;
NFAGroupLoopUNode(NFAUNode * internal, const int minMatch,
const int maxMatch, const int groupIndex, const int matchType);
virtual void findAllNodes(std::map<NFAUNode*, bool> & soFar);
virtual int match(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
int matchGreedy(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
int matchLazy(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
int matchPossessive(const std::wstring & str, WCMatcher * matcher, const int curInd = 0) const;
};
#endif
windows/nfw.bat
1
2
3
4
5
6
7
8
9
@echo off
if not exist "/Program Files/nfw/" goto x86
cd "/Program Files/nfw/"
goto ret
:x86
cd "/Program Files (x86)/nfw/"
:ret
cmd
windows/nfw.iss
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
[Files]
Source: C:\Users\nathan\Documents\synced docs\Visual Studio 2008\Projects\nfw\Release\nfw.exe; DestDir: {app}; DestName: nfw.exe;
Source: C:\Users\nathan\Documents\synced docs\Visual Studio 2008\Projects\nfw\Release\nfw.bat; DestDir: {app}; DestName: nfw.bat;
[Icons]
Name: {group}\nfw.bat; Filename: {app}\nfw.bat; WorkingDir: {app};
Name: {group}\Uninstall nfw; Filename: {uninstallexe}; WorkingDir: {app};
[Setup]
AppCopyright=Nathan Adams
AppName=nfw
AppVerName=Nate's Firewall 1.1-4
DefaultDirName={pf}\nfw\
UninstallDisplayName=Nates Firewall
AppPublisher=Nathan ADams
AppVersion=1.1-4
AppContact=adamsna@datanethost.net
AppSupportPhone=7089120579
VersionInfoVersion=114
VersionInfoDescription=Nate's Firewall
VersionInfoTextVersion=1.1-4
VersionInfoCopyright=Nathan Adams
VersionInfoProductName=Nate's Firewall
VersionInfoProductVersion=114
DefaultGroupName=nfw
AppendDefaultGroupName=false
AlwaysUsePersonalGroup=true
LicenseFile=C:\Users\nathan\Documents\synced docs\Visual Studio 2008\Projects\nfw\Release\license.txt

Archive Download the corresponding diff file

Branches

Tags

Page rendered in 0.70659s using 14 queries.