Here is my version(in Java):
- It should have a number after PO BOX
- A valid PO BOX can be part of a longer address like "My address details PO BOX 123" is a valid PO BIN address.
- It can use BIN instead of BOX
import java.util.Random;
import java.util.regex.Pattern;
public class Demo {
public static final Pattern POST_OFFICE_BOX_PATTERN = Pattern.compile("([\\w\\s*\\W]*(P(OST)?.?\\s*((O(FF(ICE)?)?)?.?\\s+B(IN|OX))+))\\s*\\d+[\\w\\s*\\W]*");
public static void main(String[] args) {
testInvalidAddresses();
testValidAddresses();
}
public static void testValidAddresses() {
String[] matches = new String[]{"HC73 P.O. Box 217",
"P O Box125",
"P.O. Box 123",
"PO Box " + Math.abs(new Random().nextInt()),
"PO Bin " + Math.abs(new Random().nextInt()),
"Post Office Box 123",
"Post Office Bin 123",
"Post Off. Box 123",
"Post Box 123",
"po bin 123"};
for (String address : matches) {
boolean isPoBox = isValidPostOfficeBox(address.toUpperCase());
if (!isPoBox) {
throw new IllegalArgumentException(address);
}
}
}
public static void testInvalidAddresses() {
var noMatches = new String[]{"#123",
"Box 123",
"Box-122",
"Box122",
"P. O. Box",
"P.O. Box",
"P.O.B 123",
"P.O.B. 123",
"P.O.B.",
"P0 Box",
"PO 123",
"PO Box",
"PO-Box",
"POB 123",
"POB",
"POBOX123",
"Po Box",
"Post 123",
"Post Office Box",
"box #123",
"box 122",
"box 123",
"p box",
"p-o box",
"p-o-box",
"p.o box",
"p.o. box",
"p.o.-box",
"p.o.b. #123",
"p.o.b.",
"p/o box",
"po #123",
"po bin",
"po box",
"po num123",
"po-box",
"pobox",
"pobox123",
"post office box",
"The Postal Road",
"Box Hill",
"123 Some Street",
"Controller's Office",
"pollo St.",
"123 box canyon rd",
"777 Post Oak Blvd",
"PSC 477 Box 396",
"RR 1 Box 1020",
"PzBzzzzzzzzz",
"PzzBzzzzzzzzz",
"PzzzBzzzzzzzzz",
"PzzzzBzzzzzzzzz",
"zzzPzBzzzzzzzzz",
"zzzPzzBzzzzzzzzz",
"zzzPzzzBzzzzzzzzz",
"zzzPzzzzBzzzzzzzzz",
"P.O 123",
"Washington Post 42",
"PO binary 123",
"p b",
"p b",
"Piebert",
"Pebble",
"pb"};
for (String address : noMatches) {
boolean isPoBox = isValidPostOfficeBox(address);
if (isPoBox) {
throw new IllegalArgumentException(address);
}
}
}
public static boolean isValidPostOfficeBox(String value) {
if (value != null) {
return POST_OFFICE_BOX_PATTERN.matcher(value.toUpperCase()).matches();
}
return false;
}
}