Matcher ReplaceAll With Match Function
Build replacement text from a MatchResult inside the function form of replaceAll, so dollar signs in untrusted input can never trigger template expansion.
Code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IdMasker {
private static final Pattern ORDER_ID = Pattern.compile("(?<prefix>ORD-)(?<number>[0-9]{4,})");
public static void main(String[] args) {
String auditLog = "ORD-1001 shipped, ORD-988702 canceled, ORD-42 kept";
// 字符串版 replaceAll 的替换串带有美元符与反斜杠转义规则,输入不可信时容易踩坑。
// 函数版本直接拿到 MatchResult,返回什么就是什么,没有模板展开语义。
String masked = ORDER_ID.matcher(auditLog).replaceAll(match -> {
String number = match.group("number");
return match.group("prefix")
+ "*".repeat(number.length() - 2)
+ number.substring(number.length() - 2);
});
System.out.println(masked);
}
}How it works
Matcher ReplaceAll With Match Function keeps everything in the class IdMasker and the function main.
Statements that matter
String masked = ORDER_ID.matcher(auditLog).replaceAll(match -> {
String number = match.group("number");
return match.group("prefix")
+ "*".repeat(number.length() - 2)
+ number.substring(number.length() - 2);
});
Interactive Tools for This Topic
URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- How do you run Matcher ReplaceAll With Match Function?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.