O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Method - String replaceFirst(String regex, String replacement)

This method replaces the first substring of the subject string, which matches the given regular expression with the replacement String. As the name implies, replaceFirst replaces only the first matching occurrence of the input String. Note that we can also supply a simple String containing no regex meta character in the first argument as regex.

Calling this method is equivalent to the following call:

Pattern.compile(regex).matcher(input).replaceFirst(replacement); 
Note: We will cover the Pattern and Matcher APIs in later chapters.

A replacement string allows the use of group references, such as $1, $2, $3, and so on, for numbered references or ${groupName} for named references, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required