English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input output (I/O)

Java Reader/Writer

Java other topics

Java String replaceFirst() usage and example

Java String (String) Methods

Java String replaceFirst() method replaces the first substring that matches the regular expression in the string with the specified text.

The syntax of replaceFirst() method is:

string.replaceFirst(String regex, String replacement)

replaceFirst() parameters

The replaceFirst() method has two parameters.

  • regex - The regular expression to be replaced (can be a typical string)

  • replace - Replace the first matching substring with this string

replaceFirst() return value

  • The replaceFirst() method returns a new string in which the first match of the substring will be replaced withReplacementString (replacement).

Program1:Java String replaceFirst() method

class Main {
  public static void main(String[] args) {
      String str1 = \
      String str2 = \223Java55@";
      //Regular expression representing a number sequence
      String regex = \+";
      //The first occurrence of "aa" is replaced with "zz"
      System.out.println(str1.replaceFirst("aa", \ // zzbbaaac
      //Replace the first number sequence with a space
      System.out.println(str2.replaceFirst(regex, \ // Learn Java55@
  }
}

In the above example, \+" is a regular expression that matches a numeric sequence.

Escaping characters in replaceFirst()

The replaceFirst() method can use a regular expression or a typical string as the first parameter. This is because a typical string itself is a regular expression.

Some characters have special meanings in regular expressions. These meta-characters are:

\ ^ $ . | ? * + {} [] ()

If you need to match substrings containing these meta-characters, you can use to escape these characters \.

//The first character of + Character
class Main {
  public static void main(String[] args) {
    String str = "a+a-++b";
    //Replace the first " +"
    System.out.println(str.replaceFirst("\\+", "#")); // a#a-++b
  }
}

If you need to replace each substring that matches a regular expression, please useJava String replaceAll() Method.

Java String (String) Methods