Saturday, 1 November 2014

Compiling regular expression

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than using the 'matches' method every time. Pattern class provides two variants of 'compile' method

public static Pattern compile(String regex)
Compiles the given regular expression into a pattern.

public static Pattern compile(String regex, int flags)
Compiles the given regular expression into a pattern with the given flags.

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