Examples of the replaceFirst method

To replace only the first semi-colon with a hyphen, we can use the following:

input = input.replaceFirst(";", "-"); 

What will be the output if we have to use the replaceFirst method instead of replaceAll in the input text of "$%apple% $%banana% $%orange%" for escaping the dollar signs?

The code will become as follows:

input = input.replaceFirst("\\$", "\\\\\\$"); 

It will replace only the first $ sign; hence, the output will only have the first $ escaped as follows:

\$%apple% $%banana% $%orange% 

To replace the first dot of an IPV4 IP address with a colon, we can use the following code:

String newip = ipaddress.replaceFirst("\\.", ":"); 

Only the first dot will be replaced by a colon; hence, an IP ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.