【问题标题】:regex experession to extract complete address starting from house number if unit numbers are present如果存在单元号,则正则表达式从门牌号开始提取完整地址
【发布时间】:2021-03-29 18:15:08
【问题描述】:

如果给定字符串中存在单元号,我正在尝试从门牌号开始提取地址。

如果单元号不可用,请选择整个字符串。

const adss1 = 'U 4 21 House Ave, Suburb State 2020';

const adss2 = 'U 14 21 House Ave, Suburb State 2020';

const adss3 = '21 House Ave, Suburb State 2020';

const regEx = /(([0-9]+)((\s+[a-zA-Z,]+|\s+[a-zA-Z,.]+\s){2,10})?(\#[0-9a-z-\-]+|\#\s+[0-9\-]+|[0-9\-]+))/g;

const match1 = adss1.match(regEx)
console.log(match1)
// [ '21 House Ave, Suburb State 2020' ]
const match2 = adss2.match(regEx)
console.log(match2)
//[ '14', '21 House Ave, Suburb State 2020' ]
const match3 = adss3.match(regEx)
console.log(match3)
//[ '21 House Ave, Suburb State 2020' ]

当前的正则表达式模式适用于 adss1 和 adss3 地址类型,但不适用于 adss2 变量。

寻找改进我的正则表达式模式的建议。谢谢

【问题讨论】:

    标签: javascript regex match


    【解决方案1】:

    据我所见,一个人只想在开始时跳过所有内容,直到一个匹配空格(序列)之前的第一个数字字符,然后是一个非数字字符;然后从那里继续匹配所有内容(直到最后).../\d+\s+\D.*$/...

    function extractAddress(data) {
      return ((/\d+\s+\D.*/).exec(String(data)) || [''])[0];
    }
    console.log([
    
      'U 4 21 House Ave, Suburb State 2020',
      'U 14 21 House Ave, Suburb State 2020',
      '21 House Ave, Suburb State 2020',
    
      'hasvk 1223 21 House Ave, Suburb State 2020',
      'has vk 12 23 21 House Ave, Suburb State 2020',
      '12 23 21 House Ave, Suburb State 2020',
    
    ].map(extractAddress));
    
    console.log(`U 4 21 House Ave, Suburb State 2020
    U 14 21 House Ave, Suburb State 2020
    21 House Ave, Suburb State 2020
    hasvk 1223 21 House Ave, Suburb State 2020
    has vk 12 23 21 House Ave, Suburb State 2020
    12 23 21 House Ave, Suburb State 2020`.match(/\d+\s+\D.*$/gm));
    .as-console-wrapper { min-height: 100%!important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多