正则表达式以匹配地址中的任何字符串组

Regexp to match any group of string within an address

本文关键字:任何 字符串 地址 正则表达式      更新时间:2023-09-26

例如,如果我有这个地址; 820 10th Avenue New York, New York 10019

我想在正则表达式中匹配以下内容; 第10大道820号
820第10大道
纽约第10大道820号

以上是唯一预期的格式

到目前为止我的代码

var re = /(^'d*'D*'w*)/i; 
var str = '820 10th Avenue New York, New York 10019';

它应该像这样工作;

if(re.test('820 10th Avenue')) console.log('pass'); // pass
if(re.test('820 10th Ave')) console.log('pass'); // pass
if(re.test('820 10th')) console.log('pass'); // pass
if(!re.test('820 9th Ave')) console.log('fail'); // fail
if(!re.test('820')) console.log('fail'); // fail
  1. 如果要检查输入字符串是否是给定字符串的一部分,可以使用String.prototype.indexOf()

    var str = '820 10th Avenue New York, New York 10019';
    str.indexOf('820 10th Avenue') > -1 // true
    str.indexOf('820 10th Ave') > -1    // true
    str.indexOf('820 10th') > -1        // true
    str.indexOf('820 9th Ave') > -1     // false
    str.indexOf('820') > -1             // true
    

    更具体地说,与0进行比较以查看它是否是前缀:

    var str = '820 10th Avenue New York, New York 10019';
    str.indexOf('820 10th Ave') === 0 // true
    str.indexOf('20 10th Ave') === 0  // false
    
  2. 根据给定的示例添加模式匹配:

    function testAddress(input) {
        var address = '820 10th Avenue New York, New York 10019';
        var re = /^'d+('s'w+){2,}/;
        return re.test(input) && address.indexOf(input) === 0;
    }
    testAddress('820 10th Ave')             // true
    testAddress('820 10th Avenue')          // true
    testAddress('820 10th Avenue New York') // true
    testAddress('820 9th Ave')     // false
    testAddress('820 10th')        // false
    testAddress('820')             // false
    

我什至认为我不需要正则表达式。这对我有用!

    var str = '820 10th Avenue New York, New York 10019';
    var n = '820 10th Ave';
    var position = str.search(n);
    if (position != -1) {
        console.log('matches')
    }else{
        console.log('no match');
    }