Saturday, 1 November 2014

Match input against pattern

Patter class provide matches method to match the given input against a regular expression.

public static boolean matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.

import java.util.regex.*;

public class PatternMatch {
    public static void main(String args[]){       
        System.out.println(Pattern.matches("a*b", "b"));
        System.out.println(Pattern.matches("a*b", "ab"));
        System.out.println(Pattern.matches("a*b", "aab"));
        System.out.println(Pattern.matches("a*b", "aaabb"));
        System.out.println(Pattern.matches("a*b", "baa"));        
    }
}

Output
true
true
true
false
false

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

import java.util.regex.*;

public class PatternMatch {
    public static void main(String args[]){     
        Pattern p = Pattern.compile("a*b");
        
        Matcher m = p.matcher("aaaaab");
        System.out.println(m.matches());  
        
        m = p.matcher("aab");
        System.out.println(m.matches());  
        
         m = p.matcher("aba");
        System.out.println(m.matches());  
    }
}

Output
true
true
false


 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment