Using Regular Expression to Replace text in Java


Regular Expressions or Regex in short is an Application Programming Interface that converts strings or sequences of characters into patterns. These patterns are later used in various string manipulations such as searching, sorting, and replacing. In this article, we will see how to search for particular characters in a string and replace it with regular expressions. To facilitate this process, we can extend some of the methods of the Java String class and the Java Matcher class to make the task easier. The benefit of string-matching optimizations from these methods saves us the hassle of coding from scratch. There are three methods in which this process can be carried out as mentioned below:

Replacing one ‘fixed’ substring with Another

This is one of the simplest approaches to replacing strings. We can use the method replaceAll() to find a particular substring and replace it with another substring. For searching, we will have to wrap around the substring around Pattern.quote(). For example, we want to replace the substring “40” with “forty”.

str = str.replaceAll(Pattern.quote(“40”), “forty”);

Replacing substrings with a Fixed String

This process takes into consideration a wider range when searching and replacing for strings. The example below refers to character syntaxes of regular expressions. [0-9] represents any digit.

str = str.replaceAll(“[0-9]”, “X”); //The following example will replace any digit in the string with the character “X”.

str = str,replaceAll(“ {2,}”, “ ”);// This will replace any two consecutive whitespaces with a single whitespace.

Replacing with a Sub-part of the Matched portion

In this example, we will be removing the HTML tag without touching the contents inside the brackets.

str = str.replaceAll (“<b>([^<]*)</b>”, “$1”)

The expression “<b>([^<]*)</b>” as appears in the snippet above extracts the text <b> and </b>. Once we have got the text, the substring can be replaced with another set of characters as given in ‘$1’.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.