VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-replace-a-string-using-regex-pattern-in-java/

⇱ How to Replace a String Using Regex Pattern in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Replace a String Using Regex Pattern in Java?

Last Updated : 23 Jul, 2025

Regular Expressions (regex), in Java, are a tool, for searching, matching, and manipulating text patterns. Regex patterns are usually written as fixed strings. Based on different scenarios we may need to create a regex pattern based on a given string.

In this article, we will learn how to replace a String using a regex pattern in Java.

Step-by-step Implementation

Step 1: Import the java.util.regex package

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

Step 2: Define the regex pattern

  • Now we have to use Pattern.compile() to create a Pattern object that will represent our regex pattern.
  • After that, we have to enclose the pattern within a raw string ("\\d+") to avoid the escaping backslashes.

Step 3: Create a Matcher object

  • Now we have to use the matcher() method of Pattern object so that we can create a Matcher object that will search for matches in a string.

Step 4: Apply the replacement

Program to Replace a String Using Regex Pattern in Java

Method 1: Using replaceAll()

In this example, we will replace string "12345" with "number" by using replaceAll() method.


Output
Original String: Hello, world! 12345 world.
Modified String: Hello, world! number world.

Explanation of the Program:

  • The above Java program demonstrates replacing a string using replaceAll() and a regex pattern.
  • It starts with an input string containing numbers.
  • The program defines a regex pattern to match digits (\\d+) and a replacement string ("number").
  • It then uses replaceAll() to replace all occurrences of digits in the input string with the replacement string.
  • After that it will print the original and modified strings.

Method 2: By Using Matcher Methods

In this example we will see how we can replace all "apple" with "orange" by using matcher methods.


Output
Original String: apple, banana, apple
Modified String: orange, banana, orange

Explanation of the Program:

  • The above Java program replaces a string using Matcher and a regex pattern.
  • It starts with an input string containing multiple occurrences of the word "apple."
  • The program defines a regex pattern to match the word "apple" and a replacement string ("orange").
  • It uses Pattern.compile() method to create a pattern and Matcher to find and replace occurrences iteratively. The modified string is then printed.
Comment