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

时间:2014-12-24 18:51:38

标签: javascript regex

例如,如果我有此地址;
820 10th Avenue纽约,纽约10019

我想在regexp中匹配以下内容;
820 10th Ave
820 10th Avenue
纽约第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

2 个答案:

答案 0 :(得分:0)

我甚至不认为我需要regexp。这对我有用!

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

答案 1 :(得分:0)

  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