Home » Core Java » util » regex » Matcher replaceFirst example

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Matcher replaceFirst example

This is an example of how to use Matcher.replaceFirst(String replacement) API method to replace the first subsequence of an input sequence that matches a specified pattern with a given replacement string. Replacing the first subsequence of a String input with a given string using a Matcher implies that you should:

  • Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern.
  • Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
  • Use replaceFirst(String replacement) API method with a given String parameter to replace the first subsequence of the input sequence that matches the pattern with the given replacement string. This method first resets this matcher. It then scans the input sequence looking for a match of the pattern.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherReplaceFirst {

    public static void main(String args[]) {


  Pattern pattern = Pattern.compile("(i|I)ce");

  String str = "I love ice. Ice is my favorite. Ice Ice Ice.";

  Matcher m = pattern.matcher(str);


  String temp = m.replaceFirst("Java");





I love Java. Ice is my favorite. Ice Ice Ice.

This was an example of Matcher.replaceFirst(String replacement) API method in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments