目录

如何替换所有出现的字符串?(How to replace all occurings of a string?)

问题描述 (Problem Description)

如何替换所有出现的字符串?

解决方案 (Solution)

下面的示例演示如何使用Matcher类的replaceAll()方法替换String中所有出现的String。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("hello");
      String instring = "hello hello hello.";
      System.out.println("initial String: "+ instring);
      Matcher m = p.matcher(instring);
      String tmp = m.replaceAll("Java");
      System.out.println("String after replacing 1st Match: "+tmp);
   }
}

结果 (Result)

上面的代码示例将产生以下结果。

initial String: hello hello hello.
String after replacing 1st Match: Java Java Java.
↑回到顶部↑
WIKI教程 @2018