• Java字符串正则文本替换


    紧接上篇中的实现细节之一,文本正则替换(for 掩码脱敏)

    Code

    public static String maskReplaceAllWithPattern(String str, BaseMasker masker) {
    	if(StrUtil.isBlank(str) || null==masker.pattern()) {
    		return str;
    	}
    	Matcher matcher = masker.pattern().matcher(str);
    	boolean find = matcher.find();
    	if(!find) {
    		return str;
    	}
    	
    	// 写法1
    //		int start = 0; //关键
    //		StringBuilder sb = new StringBuilder();
    //        do {
    //        	//System.out.println("match " + masker.maskType().name());
    //        	// append before
    //            sb.append(str, start, matcher.start());
    //            // append replacement
    //			sb.append(masker.mask(matcher.group()));
    //			// loop
    //			start = matcher.end();
    //        	find = matcher.find();
    //        } while (find);
    //        // append tail
    //        if (start < str.length()) {
    //            sb.append(str, start, str.length());
    //        }
    	
    	// 写法2
    	StringBuffer sb = new StringBuffer();
    	do {
    		// System.out.println("match masker:" + masker.maskType().name());
            // append replacement
        	matcher.appendReplacement(sb, masker.mask(matcher.group()));
    		// loop
        	find = matcher.find();
        } while (find);
        // append tail
    	matcher.appendTail(sb);
    	sb.append("_").append(masker.maskType().name());
    	
    	return sb.toString();
    }
    

    说明

  • 相关阅读:
    C#
    C#
    css
    css
    css
    css
    css
    Css
    Javascript
    ASP.NET MVC
  • 原文地址:https://www.cnblogs.com/noodlerkun/p/15498450.html
Copyright © 2020-2023  润新知