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 replaceAll method

To replace all the semi-colons with hyphens, we can use the following:

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

To remove all the non-digits from the input, we can use:

input = input.replace("\\D+", ""); 

To replace all the leading and trailing commas from an input, we can use an alternation regex:

input = input.replaceAll("^,+|,+$", ""); 

To replace all the occurrences of two or more white spaces with a single space, we can use:

input = input.replaceAll("\\s{2,}, " "); 

How can we escape all the dollar signs that are just before the % character? In other words, to replace all the occurrences of $% with \$%, we can use:

input = input.replaceAll("\\$%", "\\\\\\$%"); 

Note that we are using \\\\ (four backslashes) ...

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