HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Java String replaceFirst() method example

By Lokesh Gupta | Filed Under: String class

The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).

1. String replaceFirst(String regex, String replacement) method

The String replaceFirst() method uses regular expression to find and replace the substring with replacement substring argument.

/**
* @param regex - the regular expression to which this string is to be matched
* @param replacement - the string to be substituted for the first match
*
* @return The resulting string after replacement is done
*/

public String replaceFirst(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

2. Java String replaceFirst() example

Java program to replace first occurrence of a given string or regex in string with a new substring. In given example, I am replacing first occurrence of substring “java” with upper case “JAVA” string.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String str = "Java says hello world. Java String tutorial";
        
        //Replace first occurrence of substring "Java" with "JAVA"
        String newStr = str.replaceFirst("Java", "JAVA");
        
        //Replace first occurrence of substring "a" with "A"
        String regexResult = str.replaceFirst("[a]", "A");
        
        System.out.println(newStr);
        System.out.println(regexResult);
    }
}

Program output.

JAVA says hello world. Java String tutorial
JAva says hello world. Java String tutorial

3. ‘null’ is not allowed

A 'null' is not allowed as both method arguments. It will throw NullPointerException.

public class StringExample 
{
    public static void main(String[] args) 
    {
        String str = "Java says hello world. Java String tutorial";
        
        String newStr = str.replaceFirst("Java", null);
        
        System.out.println(newStr);
    }
}

Program output.

Exception in thread "main" java.lang.NullPointerException: replacement
	at java.util.regex.Matcher.replaceFirst(Matcher.java:999)
	at java.lang.String.replaceFirst(String.java:2165)
	at com.StringExample.main(StringExample.java:9)

In this example, we learned to replace first occurrence of character in string in Java.

Happy Learning !!

References:

Java String methods and examples
Java String Doc

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap