[英]Effective solution for create array containing all groups in regex matches
我正在尋找一種創建包含所有匹配項和包含正則表達式組匹配項的數組的有效方法。
例如Regex /(1)(2)(3)/g
字符串123
預期結果['1','2','3']
我當前的代碼如下所示:
var matches = [];
value.replace(fPattern, function (a, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15) {
for(var i = 1, v; i < 15; i++){
v = eval('s' + i);
if(v){
matches.push(v);
}else{
break;
}
}
});
它可以工作,但是我不喜歡它的工作方式。
第一件事是我實際上不知道我的正則表達式變量fPattern
中將有多少個組,因此我需要定義很多不必要的變量s1, s2 ... etc
。
第二個問題是我決定使用邪惡的eval
來防止將此變量“手動”逐一推送到數組中,也許有更好的解決方案?
還有一件事-我確實嘗試使用match()
但是不幸的是,當我使用模式/(1)(2)(3)/g
,它將返回數組['123']
所以這不是我想要實現的。
謝謝!
編輯
好吧,我發現了看起來更好的東西
matches = fPattern.exec(value);
if(matches && matches.length){
for(var key in matches){
if(key !== '0'){
if(key !== 'index'){
formated += matches[key] + ' ';
}else{
break;
}
}
};
}
就像是
arrays = "123".match(/(1)(2)(3)/);
arrays.splice(0,1);
console.log(arrays);
=> Array [ "1", "2", "3" ]
match
返回一個數組,其中數組索引0
將包含整個匹配項。 從數組索引1
開始,它將包含相應捕獲組的值。
arrays.splice(0,1);
會從數組中刪除索引0
元素,即整個匹配項,結果數組將僅包含捕獲組值
使用RegExp.exec
並收集其返回值,該返回值包含主匹配項,捕獲組和主匹配項的起始索引。
function findall(re, input) {
// Match only once for non global regex
// You are free to modify the code to turn on the global flag
// and turn it off before return
if (!re.global) {
return input.match(re);
} else {
re.lastIndex = 0;
}
var arr;
var out = [];
while ((arr = re.exec(input)) != null) {
delete arr.input; // Don't need this
out.push(arr);
// Empty string match. Need to advance lastIndex
if (arr[0].length == 0) {
re.lastIndex++;
}
}
return out;
}
狀態較少/功能更多的解決方案可能是這樣的:
function findInString(string, pattern) {
return string.split('').filter(function (element) {
return element.match(pattern)
})
}
接受一個字符串進行搜索並使用正則表達式文字,返回匹配元素的數組。 因此,例如:
var foo = '123asfasff111f6';
findInString(foo, /\d/g)
將返回[ '1', '2', '3', '1', '1', '1', '6' ]
,這似乎是您正在尋找的(?)。(至少,根據以下內容)
例如Regex /(1)(2)(3)/ g字符串123預期結果['1','2','3']
您可以傳入所需的任何正則表達式文字,它應作用於數組中的每個項目,如果匹配則返回它。 如果您想輕松地推斷出狀態/可能不得不稍后重新使用以匹配不同的模式,我會采用類似的方法。 這個問題對我來說有點模糊,因此您的確切需求可能會略有不同-試圖偏離您預期的輸入和輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.