扫码一下
查看教程更方便
Regex类 replaceFirst(String replacement) 替换模式与给定替换字符串匹配的输入序列的第一个子序列。
public String replaceFirst(String replacement)
通过用替换字符串替换第一个匹配的子序列来构造的字符串,根据需要替换捕获的子序列。
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.