Use Pattern class to match in Java


The representation of the regular expressions are available in the java.util.regex.Pattern class. This class basically defines a pattern that is used by the regex engine.

A program that demonstrates using the Pattern class to match in Java is given as follows −

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("p+");
      Matcher m = p.matcher("apples and peaches are tasty");
      System.out.println("The input string is: apples and peaches are tasty");
      System.out.println("The Regex is: p+ ");
      System.out.println();
      while (m.find()) {
         System.out.println("Match: " + m.group());
      }
   }
}

Output

The input string is: apples and peaches are tasty
The Regex is: p+
Match: pp
Match: p

Now let us understand the above program.

The subsequence “p+” is searched in the string sequence "apples and peaches are tasty". The Pattern class defines the pattern that is used by the regex engine i.e. “p+”. The find() method is used to find if the subsequence i.e. p followed by any number of p is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows −

Pattern p = Pattern.compile("p+");
Matcher m = p.matcher("apples and peaches are tasty");
System.out.println("The input string is: apples and peaches are tasty");
System.out.println("The Regex is: p+ ");
System.out.println();
while (m.find()) {
   System.out.println("Match: " + m.group());
}

Updated on: 30-Jun-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements