Reputation: 301
I need to pull the 6 digit Postal code from the address.
"51 Bras Basah Road #01-01 Manulife Centre Singapore 189554"
The postal code is always 6 digit, but not surely in the last of the address.
Please help me giving a proper "java" regex to get postal code from above address.
Asmi
Upvotes: 0
Views: 4295
Reputation: 13374
Here's a regex that will find the last six digit number:
((\d{6}.*)*\s)?(\d{6})([^\d].*)?$
Of course, you will need to escape the string when compiling the pattern:
Pattern postal_code_group3 = Pattern.compile("((\\d{6}.*)*\\s)?(\\d{6})([^\\d].*)?$");
You can get the postal code from group 3 of any match.
Note that group 2 forces a whitespace before the postal code, unless the string starts with the postal code.
Group 4 takes care of anything after the postal code, and also prevents a trailing 7-or-more digit number from being matched as the postal code.
Upvotes: 0
Reputation: 1546
If you can be sure that the postal code is the only 6-digit number in your input, you should be able to get away with:
Pattern zipPattern = Pattern.compile("(\\d{6})");
Matcher zipMatcher = zipPattern.matcher("51 Bras Basah Road #01-01 Manulife Centre Singapore 189554");
if (zipMatcher.find()) {
String zip = zipMatcher.group(1);
}
Also see the API documentation of java.util.regex.Pattern.
Upvotes: 6
Reputation: 16
Here is simple regexp
(.*)((\d){6})$
First group is "51 Bras Basah Road #01-01 Manulife Centre Singapore" 2nd group is postal code (6digits)
Upvotes: 0