匹配方括号的Javascript正则表达式



尝试执行一个JS函数,该函数将生成一个形式为"{name}(n("的新名称,其中n是给定名称列表中的下一个整数值。例如,给定"Name"、"Name(1("one_answers"Name(2(",函数应返回"Name(3("。显然,使用regex功能是可行的,但我在使用括号时遇到了问题。这是我的

utilitiesService.getNextUniqueName = function (name, arr) {
var uniqueName = name;
var max = -1;
var matchStr = new RegExp('^' + name + '( \((d{1,})\)){0,1}');
arr.forEach(function (element) {
var match = element.match(matchStr);
if (match && match.length > 0) {
if (match[2] == null) { 
max = max < 0 ? 0 : max;
} else {
max =  max < Number(match[2]) ? Number(match[2]) : max;
}
}
});
if (max >= 0) {
uniqueName = uniqueName + ' (' + String(max + 1) + ')';
};
return uniqueName;
}

参数"name"-一个给出列表基本名称的字符串,"arr"-一组给出现有名称的字符串(并非所有字符串都与基本名称匹配(。匹配有效,但问题是返回的数组"match"从不包含应由最里面的"(/d{1,}("给定的数字部分。事实上,它只包含未定义的数组元素1和2。我做错了什么?

Phil在上面的评论中回答了我的问题-我在使用RegExp构造函数时未能正确转义所有特殊字符。

最新更新