Replacing All Text Matches - Java Language Basics

Java examples for Language Basics:String

Introduction

Use a regular expression pattern to obtain a Matcher object, then use the Matcher object's replaceAll() method to replace all matches with another String value.

Demo Code



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

public class Main {
    //from  w  w  w. j a  va2s  . co  m
    public static void main(String[] args) {

        String str = "I love Java 8!  Java 8 is the 8th version.";

        Pattern pattern = Pattern.compile("[0-9]");
        Matcher matcher = pattern.matcher(str);

        System.out.println("Original: " + str);
        System.out.println(matcher.matches());
        System.out.println("Replacement: " + matcher.replaceAll("7"));
    }
}

Related Tutorials