Java中实现类似javascript中传入函数正则替换

javascript中可以这样做
var str = "abcdefg123hijk567";
var str2 = str.replace( /([a-z]+)(\d+)/g,function( a , $1 , $2, $3 ){
     return $2 + $1; //交换数字和字母的位置
});
console.info( str2 );
// 显示的是: 123abcdefg567hijk


java中可以定义一个TextUtil来实现上述功能,最终可以这样调用
public class TextTest {
	public static void main(String[] args) {
		String str = "abcdefg123hijk567";
		 
		String result = TextUtil.repalce(str, "([a-z]+)(\\d+)", new Function<String, Matcher>() {
			 
			@Override
			public Object apply(String matchedText, Matcher matcher) {
				
				return matcher.group( 2 ) + matcher.group( 1 );
			}
		});
		System.out.println( result );
	}
}


TextUtil
public class TextUtil {



	public static String repalce( String str , Pattern pattern , Function<String ,Matcher  > fun){
		Matcher matcher = pattern.matcher( str );
		String all = null ; 
		StringBuffer sb =new StringBuffer();
		while( matcher.find()){
			all = matcher.group(0); 
			String replace = (String)fun.apply( all , matcher );			
			matcher.appendReplacement(sb, replace==null?"":replace );
		}
		matcher.appendTail(sb); 
		return sb.toString();  
	}
	public static String repalce( String str , String pattern , Function<String ,Matcher  > fun){
		 Pattern p  = Pattern.compile( pattern);
		 return repalce( str , p ,fun);
	 
	}

}


Function
public interface Function<T,K> {
	public Object apply(T t,K k);
}
 

猜你喜欢

转载自chpn.iteye.com/blog/2266196