A greedy qualifier in Java Regular Expressions


A greedy qualifier repeats the specified token as many times as possible and then the engine backtracks and the greedy qualifier gives up matches to eventually find the required match.

The regex "(\w+)(\d)(\w+)" is used to find the match in the string "EarthHas1Moon".

A program that demonstrates this 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[]) {
      String str = "EarthHas1Moon";
      String regex = "(\w+)(\d)(\w+)";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(str);
      m.find();
      System.out.println(m.group(1));
      System.out.println(m.group(2));
      System.out.println(m.group(3));
   }
}

Output

EarthHas
1
Moon

Now let us understand the above program.

The regex is “(\w+)(\d)(\w+)”. This is searched in the string sequence "EarthHas1Moon". The find() method is used to find if the regex is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:

String str = "EarthHas1Moon";
String regex = "(\w+)(\d)(\w+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
m.find();
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));

Updated on: 30-Jul-2019

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements