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, ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.