Thursday, June 9, 2011

PO BOX Regx validator

This is a full and complete PO BOX validation regx written by me. I spend sometime to get this done and thoroughly tested this as well (Already in production :) ).

(?i)\s+p(ost)?(|((\s+)?\.(\s+)?)|\s+)o(ffice)?(|((\s+)?\.(\s+)?)|\s+)?(b(ox)?)?(\.)?\s+

Sample JAVA code for use this validate:

public class POBoxRegx {

public static void main(String[] args) {

Pattern myPattern = Pattern.compile("(?i)\\s+p(ost)?(|((\\s+)?\\.(\\s+)?)|\\s+)o(ffice)?(|((\\s+)?\.(\\s+)?)|\\s+)?(b(ox)?)?(\\.)?\\s+");
Matcher myMatcher = myPattern.matcher("I going to match this PO box here.");
boolean result = myMatcher.find();
if (result) {
System.out.println("Pattern matched!");
}
}
}

This should validate following sample patterns.

P(OST)(.)O(FFICE)(.)
P(OST)(.)O(FFICE)(.)
P(OST)(.)O(FFICE)(.)B(OX)(.)
P(OST)(.)O(FFICE)(.)B(OX)(.)

Optional fields are displaying the brackets.