代码之家  ›  专栏  ›  技术社区  ›  aless80

javascript regex:拆分标点和数字开头的地址,删除标点

  •  0
  • aless80  · 技术社区  · 6 年前

    我不知道如何将街道号后面的地址分开。

    假设地址是以下地址之一:

    str='street name, 12B, 1234, The Hague, the Netherlands'
    str2='street name 12B 1234AB The Hague,   the Netherlands'
    str3='street name 12B 1234AB, $ ^ The Hague, the Netherlands'
    

    我想将这些地址拆分为:

    1)逗号,最好是非字母/标点符号(例如;^@)。应拆除这些分离器;
    2)可以后面跟字母而不删除的数字。

    预期结果:

    ['street name', '12B', '1234', 'The Hague', 'the Netherlands']
    

    我正在尝试str.split(/(\d+[a-z a-z]*)/g)上的变体,它仍然保留类似“,”(为什么?).
    我还尝试了分隔符1和2之间的“或”运算符,但没有成功。
    这个更接近:

    str.split(/(\d+[a-zA-Z]*[,])/g).map(x=>x.trim().replace(/[,.;]/g,''))
    [ "street name, ", "12B,", " ", "1234,", " The Hague, the Netherlands" ]
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   trincot Jakube    6 年前

    而不是 split 你也可以看看 match . 这是你拿的东西 比赛 使用此正则表达式:

    /\d\w*|\w+( +[a-z]\w*)*/gi
    

    function parts(str) {
        return str.match(/\d\w*|\w+( +[a-z]\w*)*/gi);
    }
    
    const tests = [
        'street name, 12B, 1234, The Hague, the Netherlands',
        'street name 12B 1234AB The Hague,   the Netherlands',
        'street name 12B 1234AB, $ ^ The Hague, the Netherlands'
    ];
    
    for (const str of tests) console.log(parts(str));