Java: Replace a string from multiple replaced strings to multiple substitutes

本文介绍了一个实用的Java工具类,该工具类能够实现从多个待替换字符串到多个替代字符串的批量转换。通过正则表达式的应用,使得字符串的批量替换变得高效且便捷。

Provide helper methods to replace a string from multiple replaced strings to multiple substitutes

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringHelper {
    
    /**
     * This is test method to replace a string from:
     * aaa > zzz
     * \t > /t
     * \r > /r
     * \n > /n
     */
    public static void run()
    {
        
        String[] replacedStrings = new String[] {"aaa", "\t", "\r", "\n"};
        String[] replacements = new String[] {"zzz", "/t", "/r", "/n"};
    
        Pattern pattern = getReplacePattern(replacedStrings);
        
        // The result is "zzza/tb/rc/nd/te/nf"
        System.out.println(replace("aaaa\tb\rc\nd\te\nf", pattern, replacedStrings, replacements));
        
        // The result is "zzza/tb/rc/nd/te/nf/r"
        System.out.println(replace("aaaa\tb\rc\nd\te\nf\r", pattern, replacedStrings, replacements));
    }
    
    /**
     * Return a Pattern instance from a specific replaced string array.
     * @param replacedStrings replaced strings
     * @return a Pattern instance
     */
    public static Pattern getReplacePattern(String[] replacedStrings)
    {
        if (replacedStrings == null || replacedStrings.length == 0) return null;
        
        String regex = "";
        for (String replacedString : replacedStrings)
        {
            if (regex.length() != 0)
            {
                regex = regex + "|";
            }
            regex = regex + "(" + replacedString + ")";
        }
        regex = regex + "";

        return Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE);
    }
    

    /**
     * Replace a string.
     * @param value the string.
     * @param pattern the Pattern instance.
     * @param replacedStrings the replaced string array.
     * @param replacements the replacement array.
     * @return
     */
    public static String replace(String value, Pattern pattern, String[] replacedStrings, String[] replacements)
    {
        if (pattern == null) return value;
        if (replacedStrings == null || replacedStrings.length == 0) return value;
        if (replacements == null || replacements.length == 0) return value;
        
        if (replacedStrings.length != replacements.length) 
        {
            throw new RuntimeException("replacedStrings length must same as replacements length.");
        }
        
        Matcher matcher = pattern.matcher(value);
        StringBuffer buffer = new StringBuffer();
        int lastIndex = 0;
        
        while (matcher.find()) {
            buffer.append(value.subSequence(lastIndex,  matcher.start()));
            lastIndex = matcher.end();

            String group = matcher.group();
             
            for (int i = 0; i < replacedStrings.length; i++)
            {
                if (group.equals(replacedStrings[i]))
                {
                    buffer.append(replacements[i]);
                    break;
                }
            }
         }
         
         buffer.append(value.subSequence(lastIndex, value.length()));
         return buffer.toString();
    }
}

转载于:https://www.cnblogs.com/steven-yang/p/5345296.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值