捕获正则表达式的一个或多个匹配项(由捕获组外的字符表示)

Capture one or more occurrences of a regex expression (as denoted by characters outside the capture group)?

本文关键字:字符 表示 正则表达式 一个      更新时间:2023-09-26
    var title = '[string A][string B] the rest of the title'
    var myRegexp = /'[(.*)']/g;
    var match = myRegexp.exec(title);
    console.log(match);  // prints: 'string A][string B', and not: 'string A', 'string B'

我正在寻找一个正则表达式来捕获一个或多个由一对方括号表示的字符串(在 javascript 中(。我该如何实现此目的?

备用标题大小写包括:">[字符串 A] 一些文本 [字符串 B]"和"[字符串 A] 但没有字符串 b">

谢谢

您需要在循环中调用exec以使用此正则表达式进行多次匹配:

var re = /'[([^']]*)/g; 
var str = '[string A][string B] the rest of the title';
var m;
var matches = [];
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex)
        re.lastIndex++;
    matches.push(m[1]);
}
console.log(matches);
//=> ["string A", "string B"]

你需要让它不贪婪或使用否定的字符类而不是.*

/'[.*?']/g

演示:https://regex101.com/r/tV9qJ3/1

/'[[^']]*']/g

演示:https://regex101.com/r/tV9qJ3/2