gpt4 book ai didi

javascript - 任何数字的正则表达式,不包括特定数字

转载 作者:行者123 更新时间:2023-12-01 13:52:42 27 4
gpt4 key购买 nike

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

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

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

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

我应该如何更改表达式以匹配我要查找的数字。此外,是否有更好的方法在字符串中查找这些数字?

最佳答案

How should I change the expression to match the numbers I want to find. Additionally, is there a better way to find those numbers in a string?

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

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

Demo

关于javascript - 任何数字的正则表达式,不包括特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006738/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com