如,有一个字符串"abcdefg" 现在的要求是把"abc"变成"efg" 把"efg"变成"xyz" 怎么搞? 即目标串为:"efgdxyz" (PS:replaceAll会导致同步问题,就是说"abc"变成"efg"后,立刻又变成的"xyz")
public class Hello { public static void main(String[] args) { String str = "abcdefg"; str = str.replaceAll("efg", "xyz"); str = str.replaceAll("abc", "efg"); System.out.println(str); } }
1 "abcdefg".replaceAll("efg", "xyz").replaceAll("abc", "efg")
static void replace() { Pattern p = Pattern.compile("abc|efg"); Matcher m = p.matcher("abcdefg"); StringBuffer sb = new StringBuffer(); while (m.find()) { if(m.group().equals("abc")) m.appendReplacement(sb, "efg"); else if(m.group().equals("efg")) m.appendReplacement(sb, "xyz"); } m.appendTail(sb); System.out.println(sb.toString()); }
|