A Reluctant qualifier in Java Regular Expressions


The reluctant qualifier starts with the shortest string size as possible. If a match is found by the engine, the process continues to find more matches otherwise the engine adds a character to the searched string section and tries again. This continues until a match is obtained or the string is used up.

The regex "B+?" is used to find the match in the string "SkyIsBlue".

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 regex = "B+?";
      String str = "SkyIsBlue";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(str);
      while (m.find()) {
         System.out.println("Match String starts at index: " + m.start());
      }
   }
}

Output

Match String starts at index: 5

Now let us understand the above program.

The regex is “B+?”. This is searched in the string sequence "SkyIsBlue". The find() method is used to find if the regex is in the input sequence and its index is printed. A code snippet which demonstrates this is as follows:

String regex = "B+?";
String str = "SkyIsBlue";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while(m.find()) {
   System.out.println("Match String starts at index: " + m.start());
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements