blob: 3d279d8de678e0fba3fb09945c6fd62cb46d4af7 (
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
|
package bjc.utils.parserutils.defines;
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import bjc.utils.data.CircularIterator;
/**
* An iterated find/replace, using a circular assortment of replacements.
*
* @author Ben Culkin
*/
public class IteratedDefine implements UnaryOperator<String> {
private Pattern patt;
private Iterator<String> repls;
/**
* Create a new iterated define.
*
* @param pattern
* The pattern to use for matching.
* @param circular
* Whether or not to loop through the list of replacers, or just
* repeat the last one.
* @param replacers
* The set of replacement strings to use.
*/
public IteratedDefine(Pattern pattern, boolean circular, String... replacers) {
patt = pattern;
repls = new CircularIterator<>(Arrays.asList(replacers), circular);
}
@Override
public String apply(String ln) {
Matcher mat = patt.matcher(ln);
StringBuffer sb = new StringBuffer();
while(mat.find()) {
String repl = repls.next();
mat.appendReplacement(sb, repl);
}
mat.appendTail(sb);
return sb.toString();
}
}
|