目录

如何计算替换首次出现的String?(How to count replace first occourance of a String?)

问题描述 (Problem Description)

如何计算替换首次出现的String?

解决方案 (Solution)

下面的示例演示如何使用Matcher类的replaceFirst()方法替换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.replaceFirst("Java");
      System.out.println("String after replacing 1st Match: " +tmp);
   }
}

结果 (Result)

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

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