regex

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

  

  System.out.println(temp);

  
    }
}

Output:

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

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

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button