Saturday 1 November 2014

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

No comments:

Post a Comment