cool
cool

Reputation: 143

PO box Regex Expression

I am very new to regular expressions. I have the following regex to check for PO box in my code:

  var pattern  = @"^(?:Post(?:al)? (?:Office )?|P[. ]?O\.? )?Box\b"



if (pattern.IsMatch(subjectString) {
    Console.WriteLine("The value does not appear to be a street address");
} else {
    Console.WriteLine("Good to go");
}

Its checking for all of these:

Post Office Box

Postal Box

post box

P.O. box

P O Box

Po. box

PO Box

Box

Everything is fine except the above expression is checking for Box springs , Box Valley. I dont want this expression to check for box alone. The box should be prefixed by Po or Post box or postal box or post office box. If someone writes only box 123 or box valley then it should not check that. How can I modify the above expression to achieve this.

Upvotes: 0

Views: 1151

Answers (1)

Andy
Andy

Reputation: 658

It sounds like you were happy with your regex matching P O Box without numbers at the end since you didn't call that out as an issue. Based on that, here is a link to a solution in regex101.com: https://regex101.com/r/Gy2ba6/1

That site will give a MUCH better explanation than I have space for here. Basically, at the end match an optional whitespace character followed by at least 1 digit followed by the end character.

const strings = [
"Post Office Box",
"Postal Box",
"post box",
"P.O. box",
"P O Box",
"Po. box",
"PO Box",
"Box",
"PO Box 123",
"Box springs",
"Box Valley"
];

const pattern = /^(?:Post(?:al)? (?:Office )?|P[. ]?O\.? )?Box(?:\s\d+)?$/i;

for (const string of strings) {
  const suffix = pattern.test(string) ? "matches" : "does not match";
  console.log(string, suffix);
}

Upvotes: 3

Related Questions