捕获一次或多次出现的正则表达式(由捕获组外的字符表示)?

时间:2016-01-06 22:19:00

标签: javascript regex

{{1}}

我正在寻找一个正则表达式来捕获由一对方括号表示的一个或多个字符串(在javascript中)。我该如何做到这一点?

备用标题案例包括:'[string A] some text [string B]'和'[string A] and no string b'

感谢

2 个答案:

答案 0 :(得分:1)

您需要将其设为non-greedy或使用否定的字符类而不是.*

/\[.*?\]/g

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

/\[[^\]]*\]/g

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

答案 1 :(得分:1)

您需要在循环中调用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"]