Saturday, 1 November 2014

Greedy, Reluctant, and Possessive Quantifiers

Greedy
Reluctant
Possessive
Description
X?
X??
X?+
X, once or not at all
X*
X*?
X*+
X, zero or more times
X+
X+?
X++
X, one or more times
X{n}
X{n}?
X{n}+
X, exactly n times
X{n,}
X{n,}?
X{n,}+
X, at least n times
X{n,m}
X{n,m}?
X{n,m}+
X, at least n but not more than m times

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter the string");
        text = br.readLine();
        while(true){
            try{
                System.out.println("Enter Regular Expression");
                regex = br.readLine();
                pattern = Pattern.compile(regex);

                matcher = pattern.matcher(text);

                while (matcher.find()) {
                    System.out.print("I found the text " + matcher.group());
                    System.out.print(" starting at index " + matcher.start());
                    System.out.println(" Ending at index " + matcher.end());
                }
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Greedy Quantifier (Longest Match)
Greedy quantifier gives you the longest match in the given string. For Example for the input '12345', the valid values for '\d+' are 1, 12, 123, 1234, 12345 etc., But the Greedy quantifier gives you the longest match '12345'. Run the above program with input string '12345' like below.

Enter the string
12345
Enter Regular Expression
\d+
I found the text 12345 starting at index 0 Ending at index 5

For the input string 'xfooxxxxxxfoo' and regular expression '.*foo'.

Enter the string
xfooxxxxxxfoo
Enter Regular Expression
.*foo
I found the text xfooxxxxxxfoo starting at index 0 Ending at index 13

A greedy quantifier first matches as much as possible. So the .* matches entire string. Then the matcher tries to match the 'f' following, but there are no characters left. So it "backtracks", making the greedy quantifier match one less thing. That still doesn't match the f in the regex, so it "backtracks" one more step, making the greedy quantifier match one less thing again (leaving the "oo" at the end of the string unmatched). That still doesn't match the 'f' in the regex, so it backtracks one more step (leaving the "foo" at the end of the string unmatched). Now, the matcher finally matches the 'f' in the regex, and the 'o' and the next 'o' are matched too. So it return entire string as output for the given regular expression.

Reluctant quantifier
Reluctant quantifier starts by first consuming 'nothing'. It match as little as possible and once it finds match, it starts again the same process, until the string exhausted.

Enter the string
xxxfooxxfoo
Enter Regular Expression
.*?foo
I found the text xxxfoo starting at index 0 Ending at index 6
I found the text xxfoo starting at index 6 Ending at index 11

Enter the string
12345
Enter Regular Expression
\d+?
I found the text 1 starting at index 0 Ending at index 1
I found the text 2 starting at index 1 Ending at index 2
I found the text 3 starting at index 2 Ending at index 3
I found the text 4 starting at index 3 Ending at index 4
I found the text 5 starting at index 4 Ending at index 5

Possessive Quantifier
A possessive quantifier is just like the greedy quantifier, but it doesn't backtrack.

Enter the string
xxxfooxxfoo
Enter Regular Expression
.*+foo
Enter Regular Expression

In the above case  it starts out with .* matching the entire string, leaving nothing unmatched. Then there is nothing left for it to match with the 'f' in the regex. Since the possessive quantifier doesn't backtrack, the match fails there.

Enter the string
\d+?
Enter Regular Expression
\d+?

Enter Regular Expression


Prevoius                                                 Next                                                 Home

Possessive quantifiers

Quantifier
Example
Description
?+
X?+
X, once or not at all
*+
X*+
X, zero or more times
++
X++
X, one or more times
{n}+
X{n}+
X, exactly n times
{n,}+
X{n,}+
X, at least n times
{n,m}+
X{n,m}+
X, at least n but not more than m times

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        while(true){
            try{
                System.out.println("Enter Regular Expression");
                regex = br.readLine();
                pattern = Pattern.compile(regex);

                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                matcher.matches();

                System.out.print("I found the text " + matcher.group());
                System.out.print(" starting at index " + matcher.start());
                System.out.println(" Ending at index " + matcher.end());
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
\d{5}+
Enter the string
98765
I found the text 98765 starting at index 0 Ending at index 5
Enter Regular Expression
\d{5,8}+
Enter the string
987654
I found the text 987654 starting at index 0 Ending at index 6
Enter Regular Expression


Prevoius                                                 Next                                                 Home

Reluctant quantifiers

Quantifier
Example
Description
??
X??
X, once or not at all
*?
X*?
X, zero or more times
+?
X+?
X, one or more times
{n}?
X{n}?
X, exactly n times
{n,}?
X{n,}?
X, at least n times
{n,m}?
X{n,m}?
X, at least n but not more than m times

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        while(true){
            try{
                System.out.println("Enter Regular Expression");
                regex = br.readLine();
                pattern = Pattern.compile(regex);

                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                matcher.matches();

                System.out.print("I found the text " + matcher.group());
                System.out.print(" starting at index " + matcher.start());
                System.out.println(" Ending at index " + matcher.end());
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample output
Enter Regular Expression
\d{5}?
Enter the string
98765
I found the text 98765 starting at index 0 Ending at index 5
Enter Regular Expression
\d{5,7}?
Enter the string
987
java.lang.IllegalStateException: No match found
Enter Regular Expression
\d{5,7}?
Enter the string
987654
I found the text 987654 starting at index 0 Ending at index 6
Enter Regular Expression




Prevoius                                                 Next                                                 Home

Greedy quantifiers

Quantifier
Example
Description
?
X?
X, once or not at all
*
X*
X, zero or more times
+
X+
X, one or more times
{n}
X{n}
X, exactly n times
{n,}
X{n,}
X, at least n times
{n,m}
X{n,m}
X, at least n but not more than m times

import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        while(true){
            try{
                System.out.println("Enter Regular Expression");
                regex = br.readLine();
                pattern = Pattern.compile(regex);

                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                matcher.matches();

                System.out.print("I found the text " + matcher.group());
                System.out.print(" starting at index " + matcher.start());
                System.out.println(" Ending at index " + matcher.end());
            }
            catch(Exception e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
a?
Enter the string
a
I found the text a starting at index 0 Ending at index 1
Enter Regular Expression
a?
Enter the string
aa
java.lang.IllegalStateException: No match found
Enter Regular Expression
a*
Enter the string
aaaa
I found the text aaaa starting at index 0 Ending at index 4
Enter Regular Expression
a*b
Enter the string
aab
I found the text aab starting at index 0 Ending at index 3
Enter Regular Expression
a+b
Enter the string
aab
I found the text aab starting at index 0 Ending at index 3
Enter Regular Expression
\d{10}
Enter the string
9876543210
I found the text 9876543210 starting at index 0 Ending at index 10
Enter Regular Expression
\d{5,10}
Enter the string
9876
java.lang.IllegalStateException: No match found
Enter Regular Expression
\d{5,10}
Enter the string
987654
I found the text 987654 starting at index 0 Ending at index 6
Enter Regular Expression


Prevoius                                                 Next                                                 Home

Quantifiers

Quantifiers specify the number of occurrences to match against. 'java.lang.regex' package supports three types of quantifiers.

        a. Greedy quantifiers
        b. Reluctant quantifiers
        c. Possessive quantifiers


Prevoius                                                 Next                                                 Home

Negated Character classes

[^..] matches any character that is not listed in given class.

Ex:
[^abc] matches any character except a, b, or c

Run the harness program like below inputs.

Sample Output
Enter Regular Expression
c[^aom]
Enter the string
classic, creative, clever
I found the text cl starting at index 0 Ending at index 2
I found the text c, starting at index 6 Ending at index 8
I found the text cr starting at index 9 Ending at index 11
I found the text cl starting at index 19 Ending at index 21

Enter the string
pac

c[^aom]
Matches 2 characters 'c' which is not followed by 'a','o', 'm'.

pac
Check the string 'pac' even though 'c' in pac is not followed by 'a', 'o' and 'm' id is not printed, since there is no other character after c in 'pac.


Note
Use this program to run above sample



Prevoius                                                 Next                                                 Home

Range Of Characters

'-' is used to check for range of characters.

For Example
[a-f,A-F,0-9]{4}
Above regular expression is used to check for 32bit hexa decimal strings.

Run the harness program like below inputs.

Sample Output
Enter Regular Expression
[a-f,A-F,0-9]{4}
Enter the string
ABCD
I found the text ABCD starting at index 0 Ending at index 4

Enter the string
9aff
I found the text 9aff starting at index 0 Ending at index 4

Enter the string
10zd



Prevoius                                                 Next                                                 Home