使用RegExp从JavaScript数组返回一个精确匹配

Returning an exact match from a JavaScript array using RegExp

本文关键字:一个 RegExp JavaScript 数组 返回 使用      更新时间:2023-09-26

我有一组人,想要过滤一些条件,在这种情况下,我想搜索一个"男性",应该只返回一个结果,但是有了这个集合,我得到了所有的东西,因为正则表达式也捕获了女性。

我尝试匹配"'bmale"或"/'bmale",但没有得到任何回报。我知道我需要使用单词边界,但由于某些原因,它不起作用。

var people = [["Adelaide", 2, "yes", "female"],
           ["Ada", 2, "yes", "female"],
           ["Amanda", 1, "yes", "female"],
           ["Wolf", 3, "no", "male"],
           ["Rhonda", 1, "no", "female"]];
var isMale = function(x) {
  var myMatch = new RegExp("male");
  var test = String(x).match(myMatch);
  return String(x).match(myMatch);
}

var filteredArray=people.filter(isMale);
document.writeln(filteredArray); 

在没有必要的时候不要使用正则表达式!!

用这个代替:

var people = [
    ["Adelaide", 2, "yes", "female"],
    ["Ada", 2, "yes", "female"],
    ["Amanda", 1, "yes", "female"],
    ["Wolf", 3, "no", "male"],
    ["Rhonda", 1, "no", "female"]
];
var filteredArray = people.filter(function(el){
    return el[3] == 'male';
});

http://jsfiddle.net/XRHtZ/(检查您的控制台)

为什么不直接匹配^male,这将是行开头,紧跟着"male"?

单词"female"包含单词"male":-)

过滤器实际上应该只查看组件子数组中最后一个元素的简单值。不需要使用正则表达式;

return  x[3] === "male";

这就是你的"isMale()"函数所需要做的。

在我看来,字符串的开始/结束在这里更合适:

var myMatch = new RegExp('^male$');

如果您只想匹配恰好是"male"的条目,那么只需直接比较:

function isMale(x) {
    return(x == "male");
}

不需要使用正则表达式进行精确匹配