Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Fendadis John

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));

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.