Archive for the ‘Regular Expression’ Category

Validate Zip code Using RegEx

July 24, 2009

public class ZipCodeValidator
{
public boolean validate(String zip)
{
String zipCodePattern = “\\d{5}((-)?\\d{4})?“;
return zip.matches(zipCodePattern);
}

public static void main(String arg[])
{
ZipCodeValidator zipCodeValidate = new ZipCodeValidator();
boolean retVal = zipCodeValidate.validate(“67652-5651”);
if(retVal)
System.out.println(“valid zip code found”);
else
System.out.println(“invalid zip code found”);
}
}

Advertisements

Validate E-Mail using RegEx

July 24, 2009

public class EMailValidator
{
public boolean validate(String email)
{
//Set the email pattern string
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);
//Match the given string with the pattern
Matcher m = p.matcher(email);
//Check whether match is found
return m.matches();
}
public static void main(String arg[])
{
EMailValidator emailValidator = new EMailValidator();
boolean retVal = emailValidator.validate(“prabir.karmakar@acclaris.com“);
if(retVal)
System.out.println(“It is valid email”);
else
System.out.println(“It is invalid email”);
}
}

Regular Expression Using String Class

July 18, 2009

You can use Java Regular Expression for performaing complex validation on String objects.
You can also use matchs() method of String class for performaing Regular Expression. This function returns boolean value, return “true” if string object passes the regular expression validation other wise return “false”.
Example:
String namePattern = “[a-zA-Z_]+“;
boolean retval = name.matches(namePattern);
if(retval)
System.out.println(“Contains only alphabet”);
else
System.out.println(“validation fail”);
pattern can take only alphabet of any case and underscore of any length.