Search and Replace with Java regular expressions


Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn.

A regular expression is a special sequence of characters that help you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.

The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.

Example

Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow. " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      Pattern p = Pattern.compile(REGEX);
      //get a matcher object
      Matcher m = p.matcher(INPUT);
      INPUT = m.replaceAll(REPLACE);
      System.out.println(INPUT);
   }
}

Output

The cat says meow. All cats say meow.

Updated on: 26-Feb-2020

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements