How do you access the matched groups in a JavaScript regular expression?
I want to match a portion of a string using a regular expression and then access that parenthesized substring:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|s)format_(.*?)(?:s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript?.
The issue was that console.log
takes its parameters like a printf
statement, and since the string I was logging ( "%A"
) had a special value, it was trying to find the value of the next parameter.
您可以像这样访问捕获组:
var myString = "something format_abc";
var myRegexp = /(?:^|s)format_(.*?)(?:s|$)/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // abc
以下是您可以用来获取每个匹配的第n个捕获组的方法:
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);
var myString = "something format_abc";
var arr = myString.match(/bformat_(.*?)b/);
console.log(arr[0] + " " + arr[1]);
链接地址: http://www.djcxy.com/p/2150.html
上一篇: 你如何在正则表达式中使用变量?