0
0
JavaHow-ToBeginner · 3 min read

How to Replace Using Regex in Java: Simple Guide

In Java, you can replace text using regex with the String.replaceAll(String regex, String replacement) method. This method finds all parts of the string that match the regex pattern and replaces them with the given replacement text.
📐

Syntax

The main method to replace text using regex in Java is replaceAll. It takes two strings: the first is the regex pattern to find, and the second is the text to replace each match with.

  • regex: The pattern describing what to find.
  • replacement: The text to put instead of each match.
java
String result = originalString.replaceAll("regex", "replacement");
💻

Example

This example shows how to replace all digits in a string with the word "NUMBER" using regex.

java
public class RegexReplaceExample {
    public static void main(String[] args) {
        String text = "My phone number is 123-456-7890.";
        String replaced = text.replaceAll("\\d+", "NUMBER");
        System.out.println(replaced);
    }
}
Output
My phone number is NUMBER-NUMBER-NUMBER.
⚠️

Common Pitfalls

One common mistake is forgetting to escape special characters in the regex pattern, like backslashes. For example, to match digits, you must write "\\d" in Java strings because \ is an escape character in Java strings.

Another pitfall is using replace() instead of replaceAll(). The replace() method does not support regex and only replaces exact text.

java
/* Wrong: does not use regex, replaces exact text "\d" */
String wrong = "123".replace("\\d", "X"); // No change

/* Right: uses regex to replace digits */
String right = "123".replaceAll("\\d", "X"); // Result: "XXX"
📊

Quick Reference

MethodDescription
replaceAll(String regex, String replacement)Replaces all substrings matching regex with replacement.
replaceFirst(String regex, String replacement)Replaces only the first substring matching regex.
replace(CharSequence target, CharSequence replacement)Replaces exact text, no regex.

Key Takeaways

Use String.replaceAll() to replace text matching a regex pattern in Java.
Escape special regex characters properly in Java strings, e.g., use "\\d" for digits.
replaceAll() replaces all matches; replaceFirst() replaces only the first match.
replace() does not support regex and replaces exact text only.
Test your regex patterns to avoid unexpected replacements.