Java - String replaceFirst() 方法



Java String replaceFirst() 方法用於將 String 物件中特定模式的第一次出現替換為給定值。

此方法接受正則表示式和替換字串作為引數,搜尋當前字串中與指定正則表示式匹配的模式,並將第一次匹配項替換為給定的替換字串。匹配子字串的過程從索引 0 開始,這意味著字串的開頭。

在 Java 中,字串是內部支援字元陣列的物件。字串是一種特殊的陣列,它儲存字元,由於陣列是不可變的,因此字串也是不可變的。

注意 − 請注意,如果替換字串包含美元符號 ($) 或反斜槓 (\),結果可能與將其作為文字替換字串處理的結果不同。

語法

以下是Java String replaceFirst() 方法的語法:

public String replaceFirst(String regex, String replacement)

引數

  • regex − 這是要與此字串匹配的正則表示式。

  • replacement − 這是要替換每個匹配項的字串。

返回值

此方法返回結果字串。

使用正則表示式示例替換字串的第一次出現

以下示例演示了使用正則表示式 '!!' 作為替換子字串的 Java String replaceFirst() 方法的使用:

package com.tutorialspoint;

public class StringDemo {
   public static void main(String[] args) {
      String str1 = "!!Tutorials!!Point", str2;
      String substr = "**", regex = "!!";    
      
      // prints string1
      System.out.println("String = " + str1);    
      
      /* replaces the first substring of this string that matches the given
      regular expression with the given replacement */
      str2 = str1.replaceFirst(regex,substr);    
      System.out.println("After Replacing = " + str2);
   }
}

輸出

如果編譯並執行上述程式,它將產生以下結果:

String = !!Tutorials!!Point
After Replacing = **Tutorials!!Point

使用正則表示式示例替換字串的第一次出現

在下面的程式碼中,我們使用了 replaceFirst() 方法將字串 '.' 替換為與正則表示式 \d 匹配的第一個子字串:

package com.tutorialspoint;

public class StringDemo {
   public static void main(String[] args) {
      String s = "Akash 2786 G";
      String s1 = s.replaceFirst("\\d+", ".");
      System.out.println("The new string is: " + s1);
   }
}

輸出

如果編譯並執行上面的程式,輸出將顯示如下:

The new string is: Akash . G

使用正則表示式示例替換特殊字元

正則表示式或普通字串可以用作 replaceFirst() 方法的第一個引數。原因是普通字串本身就是一個正則表示式。

正則表示式中有一些字元具有特定含義。這些被稱為元字元。如果需要匹配包含這些元字元的子字串,可以使用“\”轉義這些字元。

package com.tutorialspoint;

public class StringDemo {
   public static void main(String[] args) {
      String s = "h^k**dg^^kl*^";
      
      // replacing the first "^ with "%"
      String s1 = s.replaceFirst("\\^", "%");
      System.out.println("The replaced string now is: " + s1);
   }
}

輸出

執行上述程式後,輸出結果如下:

The replaced string now is: h%k**dg^^kl*^

匹配字串時出現異常示例

方法引數不允許為 null。NullPointerException 將如下例所示被丟擲:

public class StringDemo {
   public static void main(String[] args) {
      String s = "Next time there won't be a next time after a certain time";
      String s1 = s.replaceFirst("Next", null);
      System.out.println("The new string is: " + s1);
   }
}

NullPointerException

上述程式的輸出如下:

Exception in thread "main" java.lang.NullPointerException: replacement
      at java.base/java.util.regex.Matcher.replaceFirst(Matcher.java:1402)
      at java.base/java.lang.String.replaceFirst(String.java:2894)
      at StringDemo.main(StringDemo.java:4)
java_lang_string.htm
廣告