javascript - 如何提取多个邮政编码?

标签 javascript node.js regex

我正在尝试从以下文本中提取多个邮政代码地名,但我不确定如何提取。

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

这是我到目前为止所拥有的,但它只提取一个邮政编码,而不是多个邮政编码。我也无法提取地址前面的地名,但我不知道如何提取。有人可以帮我吗?谢谢!

        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!');
        }

最佳答案

您可以使用否定字符类来匹配单词字符,而不匹配下划线来匹配城市名称,然后重复 0 次以上,前面加一个空格。

如果您想获取 6 位数字,可以使用捕获组。

然后匹配6位数字。

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

说明

  • ( 捕获组 1
    • [^\W\d]+ 匹配除数字之外的单词字符
    • (?:\s+[^\W\d]+)* 重复 0 次以上匹配单词字符,且前面没有 1 个以上空白字符的数字
  • ) 关闭群组
  • \s+ 匹配 1 个以上空白字符
  • ( 捕获组 2
    • \d{6} 匹配 6 位数字
  • )\b 封闭组,后跟单词边界

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");
}

关于javascript - 如何提取多个邮政编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60543937/

相关文章:

javascript - 使用 $().trigger() 并得到 TypeError : Object [object Object] has no method 'apply'

javascript - 回调如何在 Node js中真正起作用

javascript - 存储不带括号和引号的 JSON

javascript - 使用javascript删除除字母数字和空格之外的所有字符

java - 正则表达式:匹配 n-char 长重复字符序列

javascript - Sweetalert 作为一个整体组件

javascript - 使用 JavaScript 创建的样式在刷新页面之前不会应用

javascript - 在 Xul 或 javascript 中,有没有办法隐藏鼠标光标?

node.js - :Sequelize how set returned data order

mysql:比较两列