创建如下工具类:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexReplaceUtils { private RegexReplaceUtils() { } public static String regexReplace(String str, String regex, ReplaceHandler handler) { return regexReplace(str, Pattern.compile(regex), handler); } public static String regexReplace(String str, Pattern pattern, ReplaceHandler handler) { if (str == null || str.isEmpty()) { return str; } Matcher matcher = pattern.matcher(str); boolean result = matcher.find(); if (!result) { // normal char sequence return str; } int start = 0; StringBuilder sb = new StringBuilder(); do { // append before sb.append(str, start, matcher.start()); // append replacement sb.append(handler.onReplace(str.substring(matcher.start(), matcher.end()))); start = matcher.end(); result = matcher.find(); } while (result); // append tail if (start < str.length()) { sb.append(str, start, str.length()); } return sb.toString(); } public interface ReplaceHandler { Object onReplace(String token); } }
调用:
// 普通调用 RegexReplaceUtils.regexReplace("DXBTECH-\\9AD8", "\\\\[A-F0-9]{4}", new RegexReplaceUtils.ReplaceHandler() { @Override public Object onReplace(String token) { return (char) Integer.parseInt(StringUtils.substring(token, 1), 16); } }); // lambda调用 RegexReplaceUtils.regexReplace("DXBTECH-\\9AD8", "\\\\[A-F0-9]{4}", token -> (char) Integer.parseInt(StringUtils.substring(token, 1), 16))
替换结果:
"DXBTECH-\\9AD8" ===> "DXBTECH-高"
正则可视化调试网站: http://regex.dxbtech.cn/