From 2df965cd3f5764c07a6b9e412422958462bccc20 Mon Sep 17 00:00:00 2001 From: "Benjamin J. Culkin" Date: Mon, 11 Sep 2017 12:13:37 -0300 Subject: Add defines Defines are simple unary functions that apply replacements to strings. Currently, there are two types. * SimpleDefine - Replace all occurances of a pattern with a given string. * IteratedDefine - Replace occurances of a pattern with a string chosen from a series of strings. --- .../utils/parserutils/defines/IteratedDefine.java | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 BJC-Utils2/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java (limited to 'BJC-Utils2/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java') diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java new file mode 100644 index 0000000..74c4db8 --- /dev/null +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/defines/IteratedDefine.java @@ -0,0 +1,46 @@ +package bjc.utils.parserutils.defines; + +import java.util.function.UnaryOperator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import bjc.utils.data.CircularIterator; + +public class IteratedDefine implements UnaryOperator { + private Pattern patt; + + private Iterator 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 repls + * The set of replacers 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(); + } +} -- cgit v1.2.3