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

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

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