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

replaceFirst()

Example

Substitute the initial occurrence of a regular expression match with a distinct substring.

String myStr = "This is W3Schools";
String regex = "is";
System.out.println(myStr.replaceFirst(regex, "at"));

Definition and Usage

The replaceFirst() method in Java replaces the initial match of a regular expression within a string with a new substring.

In replacement strings, you can include a backreference as $n, where n represents the index of a group in the pattern. In the resulting string, occurrences of $n will be substituted with the substring matched by the respective group. Alternatively, using $0 will replace it with the entire expression. Refer to “More Examples” below for an illustration of using a backreference.

Hint: Consult the Java RegEx tutorial to grasp regular expressions.

Syntax

public String replaceFirst(String regex, String replacement)

Parameter Values

Parameter

Description

regex

Necessary: a regular expression that specifies the substrings to be sought.

replacement

Mandatory: the substring that will substitute the first match.

Technical Details

Returns:

A duplicated string where the initial substring matching the regular expression is substituted with a new substring.

Throws:

PatternSyntaxException occurs if there is a syntax error in the regular expression.

Java Version:

1.4

More Examples

Example

Employ a backreference to enclose the initial number within parentheses.

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