How to extract multiple postal codes?

scorezel789 :

I'm trying to extract multiple postal codes and place names from the following text but I'm not sure how.

Great World
1 Kim Seng Promenade, Great World, #01-138, Singapore 237994
(Nearest Drop Off at Office Lobby)
+65 6737 1366
Jem
50 Jurong Gateway Road #02-07 Singapore 608549
+65 6694 1161
Jewel Changi Airport
80 Airport Boulevard, Jewel Changi Airport,
#03-214, Singapore 819666
+65 6241 3353
Junction 8 Shopping Centre
9 Bishan Place #01-41 Singapore 579837
+65 6356 5228
Jurong Point Shopping Centre
63 Jurong West Central 3 #B1-68
Singapore 648331
+65 6861 1811

This is what I have so far but it only extracts one postal code instead of multiple postal codes. I am also having trouble extracting the place name just before the address but I'm not sure how. Can someone assist me in this? Thanks!

        var singAddrArray = [];// 
        var extractPostalRegex = "\\s\\s\\b\\d{6}\\b|Singapore\\s+\\d{6}";
        var postal = text.match(extractPostalRegex);
        postal, result = postal[0].toString().replace(/[a-zA-Z]+\s+/g,'');
        var sixDigitRegex = "\\b\\d{6}\\b";

        if (result.match(sixDigitRegex)) {
          singAddrArray.push(result);
          console.log(singAddrArray);
          console.log('sing address match!');
        } else {
          console.log('no matches found!');
        }
The fourth bird :

You might use a negated character class to match word chars without matching an underscore to match a city name followed by repeating that 0+ times preceded by a space.

If you want to get the 6 digits, you could use a capturing group.

Then match the 6 digits.

([^\W\d]+(?:\s+[^\W\d]+)*)\s+(\d{6})\b

Explanation

  • ( Capture group 1
    • [^\W\d]+ Match a word char except digits
    • (?:\s+[^\W\d]+)* Repeat 0+ times matching a word char without digits preceded by 1+ whitespac chars
  • ) Close group
  • \s+ Match 1+ whitespace chars
  • ( Capture group 2
    • \d{6} Match 6 digits
  • )\b Close group followed by a word bounary

Regex demo

let str = `Great World
1 Kim Seng Promenade, Great World, #01-138, Singapore 237994
(Nearest Drop Off at Office Lobby)
+65 6737 1366
Jem
50 Jurong Gateway Road #02-07 Singapore 608549
+65 6694 1161
Jewel Changi Airport
80 Airport Boulevard, Jewel Changi Airport,
#03-214, Singapore 819666
+65 6241 3353
Junction 8 Shopping Centre
9 Bishan Place #01-41 Singapore 579837
+65 6356 5228
Jurong Point Shopping Centre
63 Jurong West Central 3 #B1-68
Singapore 648331
+65 6861 1811`;

const regex = /([^\W\d]+(?:\s+[^\W\d]+)*)\s+(\d{6})\b/g;

while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }
  console.log("Full match: " + m[0]);
  console.log("City: " + m[1]);
  console.log("Postal code: " + m[2]);
  console.log("\n");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29987&siteId=1