---
title: "Java中实现类似javascript中传入函数正则替换"
author: "chpn"
date: "2015-12-24T14:28:32Z"
tags: ["Java", "JavaScript"]
categories: ["编程语言"]
slug: "java-javascript"
draft: false
lastmod: "2015-12-24T14:28:32Z"
id: 2266196
url: "https://chpn.iteye.com/blog/2266196"
---

javascript中可以这样做 \[code="js"] var str = "abcdefg123hijk567"; var str2 = str.replace( /(\[a-z]+)(\\d+)/g,function( a , $1 , $2, $3 ){ return $2 + $1; //交换数字和字母的位置 }); console.info( str2 ); // 显示的是： 123abcdefg567hijk \[/code] java中可以定义一个TextUtil来实现上述功能，最终可以这样调用 \[code="java"] public class TextTest { public static void main(String\[] args) { String str = "abcdefg123hijk567"; String result = TextUtil.repalce(str, "(\[a-z]+)(\\\\d+)", new Function() { @Override public Object apply(String matchedText, Matcher matcher) { return matcher.group( 2 ) + matcher.group( 1 ); } }); System.out.println( result ); } } \[/code] TextUtil \[code="java"] public class TextUtil { public static String repalce( String str , Pattern pattern , Function 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 fun){ Pattern p = Pattern.compile( pattern); return repalce( str , p ,fun); } } \[/code] Function \[code="java"] public interface Function { public Object apply(T t,K k); } \[/code]