用于匹配特定字符串后跟范围中的数字的组合的正则表达式是什么



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

例如

它应该只匹配iOS8,iOS9,iOS10,iOS11,iOS12,iOS13

字符串 - iOS |范围 - 8 到 13

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

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

演示

测试

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]$

演示 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}`);
    });
}

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

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

最新更新