How to validate PO Box Address Variations With Java Regular Expressions?

Address validation in Java could be a little tricky thing if you are unwilling to use Java Regular Expression. This is because of complexity caused by the variations of the components of the address that people can use.

In this tutorial, we will focus on doing the PO Box validation in an address using regular expressions in Java. The tutorial contains test cases for variations of the PO Box formats.

package com.kushal.tools;
/**
 * @author Kushal Pauduyal
 * Created on: 05/11/2011
 * Last Modified On: 05/11/2011
 * 
 * This class contains method and unit tests to validate the PO Box in an address.
 * The regular expression can validate several different variations of PO Boxes.
 * This should pretty much satisfy all international PO Box numbers, if not the 
 * pattern can be modified to satisfy one.
 */
import java.util.regex.Pattern;

public class RegexPOBoxValidation {

	/**
	 * Patterns are greatest things in Java. The following pattern can identify the Post Box
	 */
	static final String thePattern = 
"([\\w\\s*\\W]*(P(OST)?.?\\s*((O(FF(ICE)?)?)?.?\\s*(B(IN|OX|.?))|B(IN|OX))+))[\\w\\s*\\W]*";	
	
	/**
	 * 
	 * @param str - PO Box string to validate
	 * @return if the input string is a valid PO Box format.
	 */
	public static boolean isValid(String str) {
		return Pattern.matches(thePattern, str);
	}

	public static void main (String [] args ) {
		/**
		 * Doing unit test with several different PO Box usage alterations.
		 */
		String [] itemsToValidate = {
				"PO Box",
				"P O Box",
				"P. O. Box",
				"P.O.Box",
				"Post Box",
				"Post Office Box",
				"Post Office",
				"P.O.B",
				"P.O.B.",
				"POB",
				"Post Office Bin",
				"Box",
				"Bin",
				"Post",
				"Postal Code",
				"100,, P O Box Des Moines",
				" P O Box DesMoines1000",
				" P O Box Des Moines 1000",
				" Post Office Box",
				" Post Office Box  ",
				"Post Box #"};										 

		for (int index = 0; index < itemsToValidate.length; index++) {
			String item = itemsToValidate[index];
			boolean isValid = isValid(itemsToValidate[index].toUpperCase());
			System.out.println(item + " : " + (isValid ? "Valid" : "Invalid"));
		}
	}
			
}

Here is the output of this java program:

PO Box : Valid
P O Box : Valid
P. O. Box : Valid
P.O.Box : Valid
Post Box : Valid
Post Office Box : Valid
Post Office : Invalid
P.O.B : Valid
P.O.B. : Valid
POB : Valid
Post Office Bin : Valid
Box : Invalid
Bin : Invalid
Post : Invalid
Postal Code : Invalid
100,, P O Box Des Moines : Valid
 P O Box DesMoines1000 : Valid
 P O Box Des Moines 1000 : Valid
 Post Office Box : Valid
 Post Office Box   : Valid
Post Box # : Valid

Originally posted 2011-09-20 20:48:31.

Share

Java Tool To Compare Two Lists and Spit Out The Differences – Working Example

As a heavy java programmer, most of the time I encounter a problem where I have two lists and need to find out the differences between these two. One of the ways I sometimes quickly find out the difference is:

  • To print out the list and then use microsoft excel to compare the two columns.
  • Upload the file to temporary database tables and the run SQL query to find out the difference

As I started encountering the list compare more often, I thought of writing a tool that takes two lists and then simply print out the differences. Thus I coded the following simple piece of java program to achieve this.

The following program:

  • Can take an input of two ArrayLists presumably containing Strings, numbers of mix of both
  • It then compares the two lists and then prints out all items from first list which are not in the second lists and also prints out the items in second lists which are not in the first list

I can now use this program as often as I want and solves the hassle of me having to upload the data to database for compare or even import to excel to do the same.

Most of the programs from my blog come from my real world working experience. They are simple programs but sometimes save your huge time. Feel free to copy and modify any of the programs for your own use. Everything is open sourced and free in my blog

package com.kushal.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Kushal Paudyal Last Modified On 2011-09-16
 * 
 *         This simple utility compares two String or number lists or a list
 *         that contains either strings or number and then prints out a list of
 *         items that are in first list but not in the second list and also a
 *         list of items that are in second list but not in the first list.
 */
public class ListCompare {

	public static void main(String args[]) {
		List listA = new ArrayList();
		listA.add(1);
		listA.add(2);
		listA.add("Kushal");
		listA.add("Madan");
		listA.add("Pooja");
		listA.add("Kripa");

		List listB = new ArrayList();
		listB.add(2);
		listB.add(3);
		listB.add("Kushal");
		listB.add("Madan");
		listB.add("Jenny");
		listB.add("Betsy");

		ListCompare listComp = new ListCompare();
		listComp.compareLists(listA, listB);

	}

	public void compareLists(List firstList, List secondList) {
		Map mapForFirstList = new HashMap();
		Map mapForSecondList = new HashMap();
		Iterator firstListIterator = firstList.iterator();
		Iterator secondListIterator = secondList.iterator();
		while (firstListIterator.hasNext()) {
			String firstListKeyValue = firstListIterator.next().toString();
			/**
			 * Put the value from the list into the map, only if the same value
			 * already does not exists. That means if there are duplicates, we
			 * put only one instance into the hashmap.
			 */
			if (!mapForFirstList.containsKey(firstListKeyValue)) {
				mapForFirstList.put(firstListKeyValue, firstListKeyValue);
			}

		}

		while (secondListIterator.hasNext()) {
			String secondListKeyValue = secondListIterator.next().toString();
			/**
			 * Put the value from the list into the map, only if the same value
			 * already does not exists. That means if there are duplicates, we
			 * put only one instance into the hashmap.
			 */
			if (!mapForSecondList.containsKey(secondListKeyValue)) {
				mapForSecondList.put(secondListKeyValue, secondListKeyValue);
			}

		}
		compareAndPrintResults(mapForFirstList, mapForSecondList);

	}

	private void compareAndPrintResults(Map mapForFirstList,
			Map mapForSecondList) {
		/** Compare first map against the second one and print the difference **/
		printItemsFromFirstListThatAreNotOnSecondList(mapForFirstList,
				mapForSecondList);
		/** Compare second map against the first and print the difference */
		printItemsFromSecondListThatAreNotOnFirstList(mapForSecondList,
				mapForFirstList);

	}

	private void printItemsFromFirstListThatAreNotOnSecondList(Map mapA,
			Map mapB) {
		System.out
				.println("***Items from first list that are not in second list");
		doComparisionAndPrint(mapA, mapB);

	}

	private void printItemsFromSecondListThatAreNotOnFirstList(Map mapA,
			Map mapB) {
		System.out
				.println("***Items from second list that are not in firstList list");
		doComparisionAndPrint(mapA, mapB);

	}

	/**
	 * @param mapA
	 * @param mapB
	 * 
	 *            This method compares two hashmaps and prints out the values
	 *            from the first one that are not in the second one.
	 */
	private void doComparisionAndPrint(Map mapA, Map mapB) {
		// both maps should be non-empty for comparison.
		if (mapA != null && mapB != null) {
			Iterator mapAIterator = mapA.keySet().iterator();

			while (mapAIterator.hasNext()) {
				String key = mapAIterator.next().toString();
				if (!mapB.containsKey(key)) {
					System.out.println(key);
				}
			}
		}
	}
}

The following is the output of this program:

		***Items from first list that are not in second list
		1
		Kripa
		Pooja
		***Items from second list that are not in firstList list
		3
		Betsy
		Jenny
Blog Widget by LinkWithin

Originally posted 2011-09-16 19:15:11.

Share