将大括号内的所有文本提取到字符串数组中

extract all text inside braces into array of strings

本文关键字:提取 文本 字符串 数组      更新时间:2023-09-26

我有一个大字符串,我想从中提取圆括号内的所有部分。

假设我有一个类似的字符串

"这个(一)那个(一个二)是(三)"

我需要写一个函数,返回一个数组

["one", "one two", "three "]

我试图根据这里的一些建议编写regex,但失败了,因为我似乎只得到了第一个元素,而不是一个正确的数组,其中充满了所有元素:http://jsfiddle.net/gfQzK/

var match = s.match(/'(([^)]+)')/);
alert(match[1]);

有人能给我指正确的方向吗?我的解决方案不一定是正则表达式。

您需要一个全局正则表达式。看看这是否有帮助:

var matches = [];
str.replace(/'(([^)]+)')/g, function(_,m){ matches.push(m) });
console.log(matches); //= ["one", "one two", "three "]

match不会这样做,因为它不会在全局正则表达式中捕获组。CCD_ 2可以用于循环。

您就快到了。你只需要改变一些事情
首先,将全局属性添加到正则表达式中。现在您的正则表达式应该如下所示:

/'(([^)]+)')/g

然后,match.length将为您提供匹配的数量。要提取匹配项,请使用索引match[1] match[2] match[3]。。。

您需要使用全局标志,如果有新行,则需要使用多行,并不断exec结果,直到您在数组中获得所有结果:

var s='Russia ignored (demands) by the White House to intercept the N.S.A. leaker and return him to the United States, showing the two countries (still) have a (penchant) for that old rivalry from the Soviet era.';
var re = /'(([^)]+)')/gm, arr = [], res = [];
while ((arr = re.exec(s)) !== null) {
    res.push(arr[1]);    
}
alert(res);

小提琴


请参阅exec 上的这篇mdn文章