Use a quantifier to find a match in Java

Java 8Object Oriented ProgrammingProgramming

One of the quantifiers is the plus(+). This matches one or more of the subsequence specified with the sequence.

A program that demonstrates using the quantifier plus(+) to find a 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("o+");
      Matcher m = p.matcher("o oo ooo");
      System.out.println("The input string is: o oo ooo");
      System.out.println("The Regex is: o+ ");
      System.out.println();
      while (m.find()) {
         System.out.println("Match: " + m.group());
      }
   }
}

Output

The input string is: o oo ooo
The Regex is: o+
Match: o
Match: oo
Match: ooo

Now let us understand the above program.

The subsequence “o+” is searched in the string sequence "o oo ooo". Then the find() method is used to find if the subsequence i.e. o followed by any number of o is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("o+");
Matcher m = p.matcher("o oo ooo");
System.out.println("The input string is: o oo ooo");
System.out.println("The Regex is: o+ ");
System.out.println();
while (m.find()) {
   System.out.println("Match: " + m.group());
}
raja
Updated on 30-Jul-2019 22:30:24

Advertisements