我有一个数字列表:
2 3 11 17 21 6
与此同时,我有另一个带'-'
分隔符的数字列表:
-4-7-11-15-9-6-
我需要在javascript中找到与第一次出现匹配的正则表达式(在此示例中):
11
答案 0 :(得分:1)
你可以
var string = '-4-7-11-15-9-6-',
array = [2, 3, 11, 17, 21, 6];
var regex = new RegExp('-(' + array.join('|') + ')-');
var match = string.match(regex);
var value = match ? match[0] : undefined;
console.log()
答案 1 :(得分:1)
// returns index of first occurence of element in arr
// otherwise, returns -1
var getFirstOccurence = function (arr, str) {
// split the str by dashes and map to an array of numbers
var t = str.split("-").map(Number);
for (var i = 0; i < arr.length; i++) {
// arr[i] is in t, return its index
if (t.indexOf(arr[i]) > -1) return i;
}
// otherwise, return -1 (not in list)
return -1;
}
var str = "-4-7-11-15-9-6-",
list = [2, 3, 11, 17, 21, 6];
alert(getFirstOccurence(list, str));
// alerts 2; arr[2] is 11, which is in the list
答案 2 :(得分:0)
将第二个列表修改为(4|7|11|15|9|6)
并将其用作模式
答案 3 :(得分:0)
/(?:^|-)11(?:-|$)/
这个正则表达式将在前面,中间和末尾匹配11