[英]Regular Expression for any number excluding specific numbers
我想制作一个正则表达式,捕获每个整数(正数和负数),只要它不是以下之一:-2,-1,0,1,2或10。
所以这些应该匹配:-11,8,-4,11,15,121,3等。
到目前为止,我有这个正则表达式: /-?([^0|1|2|10])+/
它捕获了负号,但是当数字为-2或-1时它仍然会这样做,这是我不想要的。 此外,它没有捕获11。
我应该如何更改表达式以匹配我想要查找的数字。 另外,有没有更好的方法在字符串中找到这些数字?
我应该如何更改表达式以匹配我想要查找的数字。 另外,有没有更好的方法在字符串中找到这些数字?
只需使用简单的正则表达式,它将匹配字符串中的所有数字,然后过滤数字
// Define the exclude numbers list:
// (for maintainability in the future, should excluded numbers ever change,
// this is the only line to update)
var excludedNos = ['-2', '-1', '0', '1', '2', '10'];
var nos = (str.match(/-?\d+/g) || []).filter(function(no) {
return excludedNos.indexOf(no) === -1;
});
-?(?!(?:-?[012]\b)|10\b)\d+\b
只需添加一个lookahead
删除你不想要的数字。参见演示。
https://regex101.com/r/cJ6zQ3/33
var re = /-?(?!(?:-?[012]\b)|10\b)\d+\b/gm;
var str = '-2, -1, 0, 1, 2, or 10 -11, 8, -4, 11, 15, 121, 3';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
您可以使用-?(?!([012]|10)\\b)\\d+\\b
否定先行断言将解决您的问题
var res = ' -2, -1, 0, 1, 2, or 10 11, 8, -4, 11, 15, 121, 3,'.match(/-?(?!([012]|10)\\b)\\d+\\b/g); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.