目录

String replaceFirst(String replacement)

描述 (Description)

java.util.regex.Matcher.replaceFirst(String replacement)方法用替换给定替换字符串的模式替换输入序列的第一个子序列。

声明 (Declaration)

以下是java.util.regex.Matcher.replaceFirst(String replacement)方法的声明。

public String replaceFirst(String replacement)

参数 (Parameters)

  • replacement - 替换字符串。

返回值 (Return Value)

通过用替换字符串替换第一个匹配子序列而构造的字符串,根据需要替换捕获的子序列。

例子 (Example)

以下示例显示了java.util.regex.Matcher.replaceFirst(String replacement)方法的用法。

package com.iowiki;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";
   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceFirst(REPLACE);
      System.out.println(INPUT);
   }
}

让我们编译并运行上面的程序,这将产生以下结果 -

The cat says meow All dogs say meow.
↑回到顶部↑
WIKI教程 @2018