Menu

Sunday, July 10, 2011

Regular Expression - Validate only alpha numeric letters

Here is the simple program to validate the alpha numeric letters

private static void onlyAlphaNumeric () {
   //Only Alpha numeric letters
    String expression = "^[a-zA-Z0-9]+$";
    String str1 = "33345a345"; //It will match.
    String str2 = "2dF#1"; //It wont match.
    String str3 = "a333@45345"; //It wont match.
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - is a alpha numeric");
        String[] items = pattern.split(str1);
        for (String s: items)
        {
            System.out.println (s);
        }
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a alpha numeric");
    }
}