实现说明
全部逻辑都在类 TemplateExpander和函数 main中。
使用要点
- 直接运行文件,输出会带上标签,比如
raw replaceAll threw:、safe:、literal:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「quoteReplacement 让替换串回归字面量」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 raw replaceAll threw:、safe:、literal: 这类标签。
核心语句
.replaceAll(Matcher.quoteReplacement(hostile));
needle.matcher(template).replaceAll(hostile);
String template = "hello guest, bye guest";
代码示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TemplateExpander {
public static void main(String[] args) {
// a username containing $: in a replacement string it would be parsed as a group reference
String hostile = "Mallory$1";
Pattern needle = Pattern.compile("guest");
String template = "hello guest, bye guest";
// a direct replaceAll hits $1 pointing at a nonexistent group and throws IllegalArgumentException
try {
needle.matcher(template).replaceAll(hostile);
} catch (IllegalArgumentException e) {
System.out.println("raw replaceAll threw: " + e.getClass().getSimpleName());
}
// quoteReplacement escapes $ and \ into literal text, so the replacement string is written verbatim
String safe = needle.matcher(template)
.replaceAll(Matcher.quoteReplacement(hostile));
System.out.println("safe: " + safe);
// the pattern itself needs the same protection: Pattern.quote strips * of its wildcard meaning
String wildcard = "g*st";
System.out.println("literal: " + Pattern.compile(Pattern.quote(wildcard))
.matcher("g*st").replaceAll("x"));
}
}