Tuesday, June 28, 2011

Regex: Pattern and Matcher in Java

Java provides the java.util.regex package for pattern matching with regular expressions.
A regular expression defines a search pattern for strings that helps you match or find 
other strings or sets of strings, using a specialized syntax held in a pattern. They can be 
used to search, edit, or manipulate text and data.

The java.util.regex package primarily consists of the following three classes:
   Pattern Class: A Pattern object is a compiled representation of a regular expression. 
   The Pattern class provides no public constructors. To create a pattern, you must first 
   invoke one of its public static compile methods, which will then return a Pattern object. 
   These methods accept a regular expression as the first argument.

   Matcher Class: A Matcher object is the engine that interprets the pattern and performs 
   match operations against an input string. Like the Pattern class, Matcher defines no public 
   constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object.

   PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates 
   a syntax error in a regular expression pattern.

Starting with Example:
==================
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatcher {
    private static String weeks[] = {"monday","tuesday","wednesday","thursday","friday","saturday","sunday"};

    static Pattern p;
    static Matcher m;

    public static void main(String[] args) {
        System.out.println(isNumeric("9916473353"));  //true
        System.out.println(isNumeric("ad9916473353"));  //false

        System.out.println(weekPassword("monday123"));  //true
        System.out.println(weekPassword("ad9916473353"));  //false

        System.out.println(checkAlphabetPassword("monday123"));  //true
        System.out.println(checkAlphabetPassword("AbCd12"));  //true
        System.out.println(checkAlphabetPassword("12"));  //false
        
        System.out.println(check3DigitNumber("dd1d23"));  //false
        System.out.println(check3DigitNumber("45"));  //false
        System.out.println(check3DigitNumber("-124"));  //false
        System.out.println(check3DigitNumber("124"));  //true
    }
    public static boolean isNumeric(String mobNumber){
        p = Pattern.compile("[^\\d]");  //Matches only all digits [0-9]
        //p = Pattern.compile("^[0-9]");  //Matches single non-digit: [^0-9]
        //p = Pattern.compile("[0-9]");  //Matches a single digit [0-9]
        m = p.matcher(mobNumber);
        while (m.find()) {                
            return false;
        }
        return true;
    }

    public boolean isTrue(String s){ 
        return s.matches("true"); //Returns true if the string matches exactly "true"
    }

    public boolean isTrueVersion2(String s){
        return s.matches("[tT]rue"); //Returns true if the string matches exactly "true" or "True"
    }

    //Returns true if the string matches exactly "true" or "True" or "yes" or "Yes"
    public boolean isTrueOrYes(String s){
        return s.matches("[tT]rue|[yY]es");   
    }

    public boolean containsTrue(String s){
        return s.matches(".*true.*");  //Returns true if the string CONTAINS exactly "true"
    }

    public boolean isThreeLetters(String s){
        return s.matches("[a-zA-Z]{3}"); //Returns true if the string contains of three letters
        //return s.matches("[a-Z][a-Z][a-Z]");  //Same as this.
    }

    public boolean isNoNumberAtBeginning(String s){
        return s.matches("^[^\\d].*"); //Returns true if the string does not have a number at the beginning
    }

    public static boolean weekPassword(String password){
        for(int i=0;i<7;i++){  //7 days of week, takes input from week days name array
            p = Pattern.compile(weeks[i], 2); //2 is Pattern.CASE_INSENSITIVE means case-insensitive search
            m = p.matcher(password);          //1 means case sensitive
            while (m.find()) {                
                return true;    
            }
        }
        return false;
    }
    public static boolean checkAlphabetPassword(String password){
        p = Pattern.compile(".??[a-z]"); //Dangling meta char
        m = p.matcher(password);
        while(m.find()) {
            return true;    
        }
        return false;
    }
    public static boolean check3DigitNumber(String s){
        //Pattern pattern = Pattern.compile("\\d{3}");  //Contains minimum 3 consecutive numerics
        Pattern pattern = Pattern.compile("^[0-9]{3}");  //Contains exact 3 numerics
        Matcher matcher = pattern.matcher(s);
        if(matcher.find()){
            return true; 
        } 
        return false; 
    }
}
========================
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pattern1 {
    public static void main(String[] args) {
        String source="a1b2c3dBCD45Fee6743";
        String destination=null;  

        Pattern p = Pattern.compile("[^a-z]");  //Pick all except a-z
        //Pattern p = Pattern.compile("[^0-9]");  //Pick all except 0-9
        //Pattern p = Pattern.compile("[^A-Z]");  //Pick all except A-Z
        
        Matcher m = p.matcher(source);

        boolean result = m.find();        
        while(result) {
            destination=m.replaceAll("");       //Replace above match with empty characters.
            result = m.find();
        }
       System.out.println(destination); //Print after replacement. 
    }
}

//Uncomment line 11, output: BCDF
//Uncomment line 10, output: 123456743
//Uncomment line  9, output: abcdee

-----------------------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pattern2 {
    public static void main(String[] args) {
        String source="9916473353";
        String sourceWithChar="99r16d4e73353";
        String destination=null;  

        Pattern p = Pattern.compile("[0-9]{7}");  
        //Input only Digits, picks first 7 digits for replacement. 
        //If any character is not number, will return null;
        
        Matcher m = p.matcher(source);  //Without Character
        Matcher mWithChar = p.matcher(sourceWithChar); //With Character

        boolean result = m.find();        
        while(result) {
            destination=m.replaceAll("");  //Replace above match with empty characters.
            result = m.find();
        }
        System.out.println(destination); //Print after replacement. 

        destination=null;
        result = mWithChar.find();   //no match here, as source contains Characters too.            
        while(result) {              //Not entering inside while loop.      
            destination=mWithChar.replaceAll("");  //Replace above match with empty characters.
            result = mWithChar.find();
        }
        System.out.println(destination); //Print after replacement. 
    }
}
//Output:
353
null
========================================================

More help: 
http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
http://www.ocpsoft.org/opensource/guide-to-regular-expressions-in-java-part-1/
http://www.regular-expressions.info/email.html

No comments:

Post a Comment