package game.command; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternReplacer { private final String variable; private final boolean matchAll; private final Pattern pattern; private final Function function; public PatternReplacer(String variable, boolean matchAll, Function function) { this.variable = variable; this.matchAll = matchAll; this.pattern = Pattern.compile("\\$\\((" + Pattern.quote(variable) + (matchAll ? "[^\\)]*" : "") + ")\\)"); this.function = function; } public void replaceVar(StringBuffer sb) { String str = sb.toString(); sb.delete(0, sb.length()); Matcher matcher = this.pattern.matcher(str); while(matcher.find()) { String orig = matcher.group(1); String rep = this.function.apply(orig); if(rep == null) throw new RunException("Variable '%s' konnte in diesem Kontext nicht ersetzt werden", orig); matcher.appendReplacement(sb, rep); } matcher.appendTail(sb); } public String getVariable() { return this.variable; } public boolean matchesAll() { return this.matchAll; } public Pattern getPattern() { return this.pattern; } public Function getFunction() { return this.function; } }