除特定数字之外的任何数字的正则表达式

Ila*_*ala 2 javascript regex string regex-negation regex-lookarounds

我想制作一个正则表达式,捕获每个整数(正数和负数),只要它不是以下之一:-2,-1,0,1,2或10.

所以这些应该匹配:-11,8,-4,11,15,121,3等.

到目前为止,我有这个正则表达式: /-?([^0|1|2|10])+/

它捕获了负号,但是当数字为-2或-1时它仍然会这样做,这是我不想要的.此外,它没有捕获11.

我应该如何更改表达式以匹配我想要查找的数字.另外,有没有更好的方法在字符串中找到这些数字?

Tus*_*har 5

我应该如何更改表达式以匹配我想要查找的数字.另外,有没有更好的方法在字符串中找到这些数字?

只需使用简单的正则表达式,它将匹配字符串中的所有数字,然后过滤数字

// 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;
});
Run Code Online (Sandbox Code Playgroud)

演示