原文: https://howtodoinjava.com/java/string/java-string-replacefirst-example/

Java String replaceFirst()方法用给定的替换子字符串替换找到的第一个子字符串'regex',该子字符串与给定的参数子字符串(或正则表达式)匹配。 子字符串匹配过程从字符串的开头(索引 0)开始。

1. String.replaceFirst(String regex,String replacement)方法

String.replaceFirst()方法使用正则表达式查找子字符串并将其替换为replacement子字符串参数。

  1. /**
  2. * @param regex - the regular expression to which this string is to be matched
  3. * @param replacement - the string to be substituted for the first match
  4. *
  5. * @return The resulting string after replacement is done
  6. */
  7. public String replaceFirst(String regex, String replacement) {
  8. return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
  9. }

2. Java String.replaceFirst()示例

Java 程序,用新的子字符串替换字符串中给定字符串或正则表达式的第一个匹配项。 在给定的示例中,我将大写的“JAVA”字符串替换为第一次出现的子字符串“java”。

  1. public class StringExample
  2. {
  3. public static void main(String[] args)
  4. {
  5. String str = "Java says hello world. Java String tutorial";
  6. //Replace first occurrence of substring "Java" with "JAVA"
  7. String newStr = str.replaceFirst("Java", "JAVA");
  8. //Replace first occurrence of substring "a" with "A"
  9. String regexResult = str.replaceFirst("[a]", "A");
  10. System.out.println(newStr);
  11. System.out.println(regexResult);
  12. }
  13. }

程序输出。

  1. JAVA says hello world. Java String tutorial
  2. JAva says hello world. Java String tutorial

3. 不允许为null

两个方法的参数均不允许使用null。 它将抛出NullPointerException

  1. public class StringExample
  2. {
  3. public static void main(String[] args)
  4. {
  5. String str = "Java says hello world. Java String tutorial";
  6. String newStr = str.replaceFirst("Java", null);
  7. System.out.println(newStr);
  8. }
  9. }

程序输出:

  1. Exception in thread "main" java.lang.NullPointerException: replacement
  2. at java.util.regex.Matcher.replaceFirst(Matcher.java:999)
  3. at java.lang.String.replaceFirst(String.java:2165)
  4. at com.StringExample.main(StringExample.java:9)

在此示例中,我们学习了替换 Java 中字符串中首次出现的字符。

学习愉快!

参考文献:

Java String方法和示例
Java String Doc