Voora Tarun
Voora Tarun

Reputation: 1216

java regular expression extract pincode in address

I have an address which contains pincode at the end.

How to extract 6 digit pincode from address using regular expressions?

I tried using String.index() but it is not perfect. I don't know how to write reg exp syntax for extracting 6 digit string from the whole string.

Input:

19, Jogeshwari Vikhroli Link Rd, MHADA Colony 19, Powai, Mumbai, Maharashtra 400076, Mumbai,

OutPut:

400076

Upvotes: 1

Views: 4889

Answers (2)

ndnenkov
ndnenkov

Reputation: 36100

"\\b\\d{6}\\b"

Note that you have to escape the slash escaping the d/b.

  • \d - a digit
  • {6} - 6 repetitions
  • \b - a word boundary, used to limit the borders of the match. Otherwise a sequence of 7 digits would still match (as it contains 6 digits inside)

Upvotes: 7

Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

Using pattern you can extract the pin code form the address :

Pattern zipPattern = Pattern.compile("(\\d{6})");
Matcher zipMatcher = zipPattern.matcher("19, Jogeshwari Vikhroli Link Rd, MHADA Colony 19, Powai, Mumbai, Maharashtra 400076, Mumbai,");
if (zipMatcher.find()) {
    String zip = zipMatcher.group(1);
}

Upvotes: 4

Related Questions