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

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.