我已经看到了有关在正则表达式中使用变量的问题和答案,如下所示:
var re = new RegExp(yyy, 'g');
xxx.match(re);
如何添加插入符号和美元符号以实现精确匹配?
我正在迭代数组:[-10, 0, 10] 作为搜索值。所以,我正在尝试做这样的事情:
var re = new RegExp("^" + data[i] + "$", 'g');
如果我搜索 [-10, 0, 10] 数组并且搜索 0,我会得到全部三个。我只需要搜索 0:/^0$/
<小时/>这是我的完整代码和测试用例。 我正在尝试使用正则表达式/匹配来查找独特的项目。
function nonUniqueElements(data){
var arrForDeletion = [];
var strData = data.join(",");
for(var i = 0; i < data.length; i++){
var re = new RegExp(data[i], 'g');
console.log("re: " + re);
var matches = strData.match(re);
if(matches.length === 1){
arrForDeletion.push(data.indexOf(data[i]));
}
}
if(arrForDeletion.length > 0){ // If there are unique items in the input array, do not include them in the returned array.
var arrReturn = [];
data.forEach(function(item,idx){
if(arrForDeletion.indexOf(idx) === -1){
arrReturn.push(item);
}
});
console.log("arr to be returned:");
console.log(arrReturn);
return arrReturn;
}
else{ // There were no unique items in the input array.
console.log("no unique items:");
console.log(data);
return data;
}
}
/*
nonUniqueElements([1, 2, 3, 1, 3]); // == [1, 3, 1, 3]
nonUniqueElements([1, 2, 3, 4, 5]); // == []
nonUniqueElements([5, 5, 5, 5, 5]); // == [5, 5, 5, 5, 5]
nonUniqueElements([10, 9, 10, 10, 9, 8]); // == [10, 9, 10, 10, 9]
*/
nonUniqueElements([-10,10,0]); // []
最佳答案
您将获得全部 3 个值,因为对于数组中的每个条目,您都在精确搜索该值。这当然会返回所有 3 个。
如果您只想匹配恰好为 0 的值,您可以简单地执行以下操作:
const regex = new RegExp('^0$'); // Only need to compile it once
for(let i = 0; i < arr.length; i++){
arr[i].match(re);
}
或者,如果您只检查 0 值,为什么不这样做
arr[i] === 0
或 arr[i] === '0'
取决于您的输入是字符串还是数字。
关于javascript - 如何在 JavaScript 中使用带有 RegEx 的变量来使用 "^"和 "$"进行精确匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51750031/