tcr/java/src/game/command/PatternReplacer.java
2025-03-25 23:10:40 +01:00

49 lines
1.3 KiB
Java

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<String, String> function;
public PatternReplacer(String variable, boolean matchAll, Function<String, String> 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<String, String> getFunction() {
return this.function;
}
}