blob: 6ca0c743667391d3eb068fd47f6a4647aa2ac5a2 (
plain)
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
|
package bjc.dicelang.v2;
import bjc.utils.data.CircularIterator;
import java.util.Iterator;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Define implements UnaryOperator<String> {
public static enum Type {
LINE, TOKEN
}
public final int priority;
private boolean doRecur;
private boolean subType;
private Pattern predicate;
private Pattern searcher;
private Iterator<String> replacers;
private String replacer;
public Define(int priorty, boolean isSub, boolean recur,
String predicte, String searchr, Iterable<String> replacrs) {
priority = priorty;
doRecur = recur;
subType = isSub;
if(predicte != null) {
predicate = Pattern.compile(predicte);
}
searcher = Pattern.compile(searchr);
if(subType) {
if(replacrs.iterator().hasNext()) {
replacers = new CircularIterator<>(replacrs);
} else {
replacers = null;
}
} else {
Iterator<String> itr = replacrs.iterator();
if(itr.hasNext()) replacer = itr.next();
else replacer = "";
}
}
public String apply(String tok) {
if(predicate != null) {
if(!predicate.matcher(tok).matches()) {
return tok;
}
}
String strang = doPass(tok);
if(doRecur) {
if(strang.equals(tok)) {
return strang;
} else {
String oldStrang = strang;
do {
strang = doPass(tok);
} while(!strang.equals(oldStrang));
}
}
return strang;
}
private String doPass(String tok) {
Matcher searcherMatcher = searcher.matcher(tok);
if(subType) {
StringBuffer sb = new StringBuffer();
while(searcherMatcher.find()) {
if(replacers == null) searcherMatcher.appendReplacement(sb,"");
else searcherMatcher.appendReplacement(sb, replacers.next());
}
searcherMatcher.appendTail(sb);
return sb.toString();
} else {
return searcherMatcher.replaceAll(replacer);
}
}
}
|