[英]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.