繁体   English   中英

匹配特定字符串后跟数字的组合的正则表达式可能是什么?

[英]What could be the regex for matching combination of a specific string followed by number in a range?

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

例如

它应该只匹配 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"; } }));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM