Java-Wildcards with Quantifiers

Wildcards with Quantifiers

A quantifier following a subsequence of a pattern determines the possibilities for how that subsequence of a pattern can repeat. Although the previous programs show the general technique for using Pattern and Matcher, they don’t show their power. The real benefit of regular expression processing is not seen until wildcards and quantifiers are used. The next program uses a wildcard to create a pattern that will match any sequence that begins with ‘R‘ and ends with ‘X‘. To do this, it uses the dot wildcard character along with the ‘+ quantifier. You might be surprised by the output produced by the program, only one match is found, and it is the longest sequence that begins with ‘R‘ and ends with ‘X‘. You might have expected three matches: “RunX“,”RunningX” and “RunnerX“. The reason that the longer sequence is found is that, by default, find( ) matches the longest sequence that fits the pattern. This is called greedy behavior. The regular expression ‘R.+X‘ matches ‘R‘ with any number of characters up to the last ‘X‘ it finds. You can specify reluctant behavior by adding the ‘?‘ quantifier to the pattern, as shown in program two. The regular expression ‘R.+?X‘ matches ‘R‘ with any number of characters up to the first ‘X‘ it finds.

Program

 

Program Two



Program Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("R.+X");
        Matcher mat = pat.matcher("RunXRunningXRunnerX");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Program Two Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("R.+?X");
        Matcher mat = pat.matcher("RunXRunningXRunnerX");
        
        int i = 0;
        while(mat.find())
        {
            i++;
            System.out.println(i+"th subsequence  : "+mat.group());
        }
    }
}

Leave a Comment