May 2009
Intermediate to advanced
510 pages
15h
English
You want to catch addresses that contain a P.O. box, and warn users that their shipping information must contain a street address.
^(?:Post●(?:Office●)?|P[.●]?O\.?●)?Box\b
| Regex options: Case insensitive, ^ and $ match at line breaks |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Regex regexObj = new Regex(
@"^(?:Post (?:Office )?|P[. ]?O\.? )?Box\b",
RegexOptions.IgnoreCase | RegexOptions.Multiline
);
if (regexObj.IsMatch(subjectString) {
Console.WriteLine("The value does not appear to be a street address");
} else {
Console.WriteLine("Good to go");
}See Recipe 3.5 for help with implementing this regular expression with other programming languages.
The following explanation is written in free-spacing mode, so each of the meaningful space characters in the regex has been escaped with a backslash:
^ # Assert position at the beginning of a line. (?: # Group but don't capture... Post\ # Match "Post ". (?:Office\ )? # Optionally match "Office ". | # or... P[.\ ]? # Match "P" and an optional period or space character. O\.?\ # Match "O", an optional period, and a space character. )? # Repeat the group between zero and one time. Box # Match "Box". \b # Assert position at a word boundary.
| Regex options: Case insensitive, ^ and $ match at line breaks |
| Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
This regular expression matches all of the following example strings ...
Read now
Unlock full access