3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以像這樣訪問(wèn)捕獲組:
var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abc
如果有多個(gè)匹配,您可以迭代它們:
var myString = "something format_abc";
var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
match = myRegexp.exec(myString);
while (match != null) {
// matched text: match[0]
// match start: match.index
// capturing group n: match[n]
console.log(match[0])
match = myRegexp.exec(myString);
}

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是一種方法,您可以使用它來(lái)獲得每個(gè)匹配的第n個(gè)捕獲組:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
// Example :
var myString = 'something format_abc something format_def something format_ghi';
var myRegEx = /(?:^|\s)format_(.*?)(?:\s|$)/g;
// Get an array containing the first capturing group for every match
var matches = getMatches(myString, myRegEx, 1);
// Log results
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
console.log(matches);

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
關(guān)于上面的多匹配括號(hào)示例,我在找不到我想要的內(nèi)容之后在這里尋找答案:
var matches = mystring.match(/(?:neededToMatchButNotWantedInResult)(matchWanted)/igm);
在看了上面帶有while和.push()的稍微復(fù)雜的函數(shù)調(diào)用之后,我突然意識(shí)到問(wèn)題可以用mystring.replace()代替非常優(yōu)雅(替換不是重點(diǎn),甚至沒(méi)有完成,CLEAN,第二個(gè)參數(shù)的內(nèi)置遞歸函數(shù)調(diào)用選項(xiàng)是?。?/p>
var yourstring = 'something format_abc something format_def something format_ghi';
var matches = [];
yourstring.replace(/format_([^\s]+)/igm, function(m, p1){ matches.push(p1); } );
在此之后,我認(rèn)為我不會(huì)再使用.match()了。
添加回答
舉報(bào)