Sunday 2 November 2014

matches() : Match entire input sequence

public boolean matches()
Method returns true if entire sequence matched with the pattern, else false.

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 Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);
                
                System.out.println("Is pattern matched : " + matcher.matches());
                System.out.println();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
a*b
Enter the string
abbb
Is pattern matched : false

Enter the string
aaab
Is pattern matched : true

Enter the string
xb
Is pattern matched : false


Usually the regular expression 'a*b' matches b, ab, aab, aaab.....
so matches method return false for the input strings 'abbb', 'xb'. 



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment