1. 程式人生 > >長文字替換多個字串

長文字替換多個字串

package com;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
public static void main(String[] args) {
	List<String> oldStrList= new ArrayList<>(Arrays.asList(new String[]{"abc","123"})) ;
	List<String> newStrList= new ArrayList<>(Arrays.asList(new String[]{"999","888"})) ;
	String replaceALl = replaceALl(oldStrList, newStrList,"asfsdabcgfdfabchfgh312654sa123sd1fg5d4fsg");
	System.out.println(replaceALl);
}
public static String replaceALl(List<String> oldStrList, List<String>  newStrList,String regString) {
	StringBuilder reg = new StringBuilder();
	for (int i = 0; i < oldStrList.size(); i++) {
		if(i<oldStrList.size()-1) {
			reg.append(oldStrList.get(i)+"|");
		}else {
			reg.append(oldStrList.get(i));
		}
	}
	Pattern compile = Pattern.compile(reg.toString());
	Matcher m = compile.matcher(regString);
	 StringBuffer sb = new StringBuffer();
	 m.reset();
     while (m.find()) {
         String find = m.group();
         int findIndex = oldStrList.indexOf(find);
         if(findIndex!=-1) {
        	 m.appendReplacement(sb, newStrList.get(findIndex));
         }
     }
     m.appendTail(sb);
	return sb.toString();
	
}

}