Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

replaceAll()

Example

Substitute each instance of a regular expression match with a designated substring.

String myStr = “I love cats. Cats are very easy to love. Cats are very popular.”;
String regex = “(?i)cat”;
System.out.println(myStr.replaceAll(regex, “dog”));

ionMatches(int offset, String other, int otherOffset, int length)

Definition and Usage

The replaceAll() method in Java replaces every match of a regular expression within a string with a new substring.

Replacement strings may include a backreference denoted as $n, where n represents the index of a group in the pattern. Within the resulting string, occurrences of $n will be substituted with the substring matched by the corresponding group. If $0 is employed, it will be substituted with the entire expression. Refer to “More Examples” below for an illustration of using a backreference.

Suggestion: Consult the Java RegEx tutorial to gain insights into regular expressions.

Syntax

public String replaceAll(String regex, String replacement)

Parameter Values

Parameter

Description

regex

Mandatory. A regular expression that specifies the substrings to be searched for.

replacement

Necessary. The substring that will substitute each match.

Technical Details

REturns

A duplicate of the string where matches of the regular expression have been substituted with new substrings.

Throws

PatternSyntaxException occurs if the syntax of the regular expression is incorrect.

Java Version

1.4

More Examples

Example

Utilize a backreference to enclose numbers within parentheses.

String myStr = "Quest complete! Earned 30 gold and 500 experience.";
String regex = "[0-9]+";
System.out.println(myStr.replaceAll(regex, "($0)"));