如何替换所有出现的字符串?
下面的示例演示如何使用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);
}
}
上面的代码示例将产生以下结果。
initial String: hello hello hello.
String after replacing 1st Match: Java Java Java.