Java.lang.String.replaceFirst() Method

Advertisements


Description

The java.lang.String.replaceFirst() method replaces the first substring of this string that matches the given regular expression with the given replacement.

Declaration

Following is the declaration for java.lang.String.replaceFirst() method

public String replaceFirst(String regex, String replacement)

Parameters

  • regex -- This is the regular expression to which this string is to be matched.

  • replacement -- This is the string to be substituted for each match.

Return Value

This method returns the resulting string.

Exception

  • PatternSyntaxException -- if the regular expression's syntax is invalid.

Example

The following example shows the usage of java.lang.String.replaceFirst() method.

package com.tutorialspoint;

import java.lang.*;

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);
  }
}

Let us compile and run the above program, this will produce the following result:

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



Advertisements
Advertisements