import java.util.regex.Matcher; import java.util.regex.Pattern; //正则表达式替换字符方法 public class PatternReplaceExmple{ private static Pattern p ; private static Matcher m ; //str为要匹配的字符格式 public static void setPattern(String str){ p = Pattern.compile(str); } public static void setPattern(String str,int i){ p = Pattern.compile(str,i); } //str为要匹配字符串 public static void setMatcher(String str){ m = p.matcher(str); } //str为替换匹配字符格式的字符 public static String replace(String str){ StringBuffer buf = new StringBuffer(); while(m.find()){ m.appendReplacement(buf,str); } m.appendTail(buf); return buf.toString(); } }
import java.util.Date; import java.util.regex.Pattern; public class A { public static void main(String args[]){ //Pattern.CASE_INSENSITIVE为不区分大小写 PatternReplaceExmple.setPattern("jav",Pattern.CASE_INSENSITIVE ); PatternReplaceExmple.setMatcher("sdlfjjavalj adj a vaaljkJAvakljljJavA lkjlj "); System.out.println(PatternReplaceExmple.replace("haha")); } }
输出结果:sdlfjhahaalj adj a vaaljkhahaakljljhahaA lkjlj