-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomregexVisitor.js
More file actions
96 lines (85 loc) · 2.38 KB
/
CustomregexVisitor.js
File metadata and controls
96 lines (85 loc) · 2.38 KB
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
import { Parser } from "antlr4";
import RegexVisitor from "./generated/RegexVisitor.js";
import RegexParser from "./generated/RegexParser.js";
export class CustomRegexVisitor extends RegexVisitor {
constructor() {
super();
}
visitRegex(ctx) {
// Soporta múltiples alternativas con '|'
const terms = ctx.term().map(term => this.visit(term));
return terms.join('|');
}
visitTerm(ctx) {
let result = "";
for (let i = 0; i < ctx.factor().length; i++) {
result += this.visit(ctx.factor(i));
}
return result;
}
visitFactor(ctx) {
const base = this.visit(ctx.base());
if (ctx.quantifier()) {
const quantifier = this.visit(ctx.quantifier());
return base + quantifier;
}
return base;
}
visitBase(ctx) {
if (ctx.CHAR()) {
return ctx.CHAR().getText();
} else if (ctx.group()) {
return this.visit(ctx.group());
} else if (ctx.class_()) {
return this.visit(ctx.class_());
}
return "";
}
visitGroup(ctx) {
return "(" + this.visit(ctx.regex()) + ")";
}
visitClass_(ctx) {
let result = "[";
if (ctx.CARET()) {
result += "^";
}
for (let i = 0; i < ctx.classElem().length; i++) {
result += this.visit(ctx.classElem(i));
}
result += "]";
return result;
}
visitClassElem(ctx) {
if (ctx.range()) {
return this.visit(ctx.range());
} else if (ctx.CHAR()) {
return ctx.CHAR().getText();
}
return "";
}
visitRange(ctx) {
return ctx.CHAR(0).getText() + "-" + ctx.CHAR(1).getText();
}
visitQuantifier(ctx) {
if (ctx.STAR()) {
return "*";
} else if (ctx.PLUS()) {
return "+";
} else if (ctx.QUESTION()) {
return "?";
} else if (ctx.LBRACE()) {
const min = ctx.NUMBER(0).getText();
if (ctx.COMMA()) {
if (ctx.NUMBER(1)) {
const max = ctx.NUMBER(1).getText();
return `{${min},${max}}`;
} else {
return `{${min},}`;
}
} else {
return `{${min}}`;
}
}
return "";
}
}