用于匹配特定字符串和范围内数字的组合的正则表达式是什么?

时间:2019-06-15 15:06:35

标签: javascript regex

匹配特定字符串和范围内数字的组合的正则表达式是什么?

例如

它只能与iOS8,iOS9,iOS10,iOS11,iOS12,iOS13匹配

string-iOS | 范围-8到13

2 个答案:

答案 0 :(得分:3)

此表达式仅与列出的所需iOS版本匹配:

iOS[89]|iOS[1][0-3]

Demo

测试

const regex = /iOS[89]|iOS[1][0-3]/gm;
const str = `iOS7
iOS8
iOS9
iOS10
iOS11
iOS12
iOS13
iOS14`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

对于iOS1到iOS213,例如,以下表达式可能有效,并且如果要进行验证,我们将添加开始和结束锚点:

^iOS[2][1][0-3]$|^iOS[2][0]\d$|^iOS[1][0-9][0-9]$|^iOS[1-9][0-9]$|^iOS[1-9]$

Demo 2

const regex = /^iOS[2][1][0-3]$|^iOS[2][0]\d$|^iOS[1][0-9][0-9]$|^iOS[1-9][0-9]$|^iOS[1-9]$/gm;
const str = `iOS0
iOS7
iOS8
iOS9
iOS10
iOS11
iOS12
iOS13
iOS14
iOS200
iOS201
iOS202
iOS203
iOS205
iOS214`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

答案 1 :(得分:1)

一种更简单的方法是提取数值并与最小值和最大值进行比较:

var arr = ['iOS0','iOS1','iOS8','iOS12', 'iOS15', 'abc123']

console.log(arr.map(function (s) {
    if (m = s.match(/^iOS(\d+)$/)) {
        if (m[1] > 7 && m[1] < 14) {
            return s + " --> match";
        } else {
            return s + " --> no match";
        }
    } else {
        return s + " --> no match";
    }
}));