MCPcopy Create free account
hub / github.com/google/re2j / Simplify

Class Simplify

java/com/google/re2j/Simplify.java:14–178  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12import java.util.ArrayList;
13
14class Simplify {
15
16 // Simplify returns a regexp equivalent to re but without counted
17 // repetitions and with various other simplifications, such as
18 // rewriting /(?:a+)+/ to /a+/. The resulting regexp will execute
19 // correctly but its string representation will not produce the same
20 // parse tree, because capturing parentheses may have been duplicated
21 // or removed. For example, the simplified form for /(x){1,2}/ is
22 // /(x)(x)?/ but both parentheses capture as $1. The returned regexp
23 // may share structure with or be the original.
24 static Regexp simplify(Regexp re) {
25 if (re == null) {
26 return null;
27 }
28 switch (re.op) {
29 case CAPTURE:
30 case CONCAT:
31 case ALTERNATE:
32 {
33 // Simplify children, building new Regexp if children change.
34 Regexp nre = re;
35 for (int i = 0; i < re.subs.length; ++i) {
36 Regexp sub = re.subs[i];
37 Regexp nsub = simplify(sub);
38 if (nre == re && nsub != sub) {
39 // Start a copy.
40 nre = new Regexp(re); // shallow copy
41 nre.runes = null;
42 nre.subs = Parser.subarray(re.subs, 0, re.subs.length); // clone
43 }
44 if (nre != re) {
45 nre.subs[i] = nsub;
46 }
47 }
48 return nre;
49 }
50 case STAR:
51 case PLUS:
52 case QUEST:
53 {
54 Regexp sub = simplify(re.subs[0]);
55 return simplify1(re.op, re.flags, sub, re);
56 }
57 case REPEAT:
58 {
59 // Special special case: x{0} matches the empty string
60 // and doesn't even need to consider x.
61 if (re.min == 0 && re.max == 0) {
62 return new Regexp(Regexp.Op.EMPTY_MATCH);
63 }
64
65 // The fun begins.
66 Regexp sub = simplify(re.subs[0]);
67
68 // x{n,} means at least n matches of x.
69 if (re.max == -1) {
70 // Special case: x{0,} is x*.
71 if (re.min == 0) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…