Java教程

Java String replaceFirst()

Java String replaceFirst()

Java String replaceFirst() 方法用指定的文本替换与字符串正则表达式匹配的第一个子字符串。
replaceFirst() 方法的语法是:
string.replaceFirst(String regex, String replacement)
这里, stringString 类的对象。

replaceFirst() 参数

replaceFirst() 方法有两个参数。
regex-要替换​​的正则表达式(可以是典型的字符串) 替换-第一个匹配的子字符串被替换为这个字符串

replaceFirst() 返回值

replaceFirst() 方法返回一个新字符串,其中第一次出现的匹配子字符串被替换为 replacement 字符串。

示例 1: Java 字符串 replaceFirst()

class Main {
  public static void main(String[] args) {
      String str1 = "aabbaaac";
      String str2 = "Learn223Java55@";
      // regex for sequence of digits
      String regex = "\\d+";
      // the first occurrence of "aa" is replaced with "zz"
      System.out.println(str1.replaceFirst("aa", "zz")); // zzbbaaac
      // replace the first sequence of digits with a whitespace
      System.out.println(str2.replaceFirst(regex, " ")); // Learn Java55@
  }
}
在上面的例子中, "\\d+" 是一个匹配数字序列的正则表达式。要了解更多信息,请访问 Java 正则表达式。

replaceFirst() 中的转义字符

replaceFirst() 方法可以将正则表达式或典型字符串作为第一个参数。这是因为典型的字符串本身就是一个正则表达式。
在正则表达式中,有些字符具有特殊含义。这些元字符是:
\ ^ $ . | ? * + {} [] ()
如果需要匹配包含这些元字符的子串,可以使用 \对这些字符进行转义。
// Program to the first + character
class Main {
  public static void main(String[] args) {
    String str = "a+a-++b";
    // replace the first "+" with "#"
    System.out.println(str.replaceFirst("\\+", "#")); // a#a-++b
  }
}
如果您需要替换与正则表达式匹配的每个子字符串,请使用Java String replaceAll() 方法。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4