java tutorial - Java replaceFirst() method - java programming - learn java - java basics - java for beginners



Description

The replaceFirst() method — replaces the first substring of this string, which corresponds to the specified regular expression, with this substitution, in other words, the method in Java allows you to replace the first occurrence of a word or phrase in a string.

Syntax

Syntax method:

public String replaceFirst(String regex, String replacement)
click below button to copy the code. By - java tutorial - team

Options

Detailed information about the parameters:

  • regex is a regular expression to which this string must match;
  • replacement is a string that will replace the expression found.

Return value

  • In Java, replaceFirst () returns the result string.

Sample Code

import java.io.*;
public class Test {

public static void main(String args[]) {
       String Str1 = new String("Welcome to wikitechy.com");

System.out.print("Return value:" );
System.out.println(Str1.replaceFirst("(. *) wikitechy (. *)",
"IAMGROOT"));

System.out.print("Return value:" );
System.out.println(Str1.replaceFirst("wikitechy.com", "wikitechy tutorials"));

String Str2 = new String("Welcome to wikitechy.com! Welcome to wikitechy.com!");

System.out.print("Return value:" );
System.out.println(Str2.replaceFirst("Welcome to wikitechy.com!", "wikitechy tutorials!"));
}
}
click below button to copy the code. By - java tutorial - team

Output

Return value:Welcome to wikitechy.com
Return value:Welcome to wikitechy tutorials
Return value:wikitechy tutorials! Welcome to wikitechy.com!

Related Searches to Java replaceFirst() method