• java怎么正则替换,怎么对正则匹配值做自定义处理(自定义正则替换工具类)


    创建如下工具类:

    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/

  • 相关阅读:
    <c:forEach 的常用整理
    <div>
    HTML <td> 标签的 rowspan 属性
    ap-client.xml要配
    @Autowired
    hasResultError
    使用 EclEmma 进行覆盖测试
    IE调试网页之三:使用 F12 工具控制台查看错误和状态 (Windows)
    different between<A Href> and <jsp: forward>
    <button>与<input type="button">的区别
  • 原文地址:https://www.cnblogs.com/parasis/p/13278661.html
Copyright © 2020-2023  润新知