August 2012
Intermediate to advanced
609 pages
19h 16m
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(?:al)?●(?: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(?:al)? (?: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 running a regular expression match test like this with other programming languages. Recipe 3.4 explains how to set the regex options used here.
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(?:al)?\ # Match "Post " or "Postal ". (?: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. )? # Make the group optional. Box # Match "Box". \b # Assert position at a word boundary.
| Regex options: Case insensitive, ^ and $ match at line breaks, free-spacing |
| Regex flavors: .NET, Java, XRegExp, PCRE, ... |
Read now
Unlock full access