[英]extract all text inside braces into array of strings
I have a big string from which I would like to extract all parts that are inside round braces. 我有一个大字符串,我想从中提取圆括号内的所有部分。
Say I have a string like 说我有一个字符串
"this (one) that (one two) is (three )"
“这(一)那(一二)是(三)”
I need to write a function that would return an array 我需要编写一个返回数组的函数
["one", "one two", "three "]
I tried to write a regex from some advice found here and failed, since I seem to only get the first element and not a proper array filled with all of them: http://jsfiddle.net/gfQzK/ 我尝试从这里找到的一些建议写一个正则表达式并且失败了,因为我似乎只得到第一个元素而不是一个充满所有这些的正确数组: http : //jsfiddle.net/gfQzK/
var match = s.match(/\(([^)]+)\)/);
alert(match[1]);
Could someone point me in the right direction? 有人能指出我正确的方向吗? My solution does not have to be regular expression.
我的解决方案不一定是正则表达式。
You need a global regex. 你需要一个全局正则表达式。 See if this helps:
看看这是否有帮助:
var matches = [];
str.replace(/\(([^)]+)\)/g, function(_,m){ matches.push(m) });
console.log(matches); //= ["one", "one two", "three "]
match
won't do as it doesn't capture groups in global regex. match
不会,因为它不捕获全局正则表达式中的组。 replace
can be used to loop. replace
可以用于循环。
You are almost there. 你快到了。 You just need to change a few things.
你只需要改变一些事情。
First, add the global attribute to your regex. 首先,将全局属性添加到正则表达式中。 Now your regex should look like:
现在你的正则表达式看起来像:
/\(([^)]+)\)/g
Then, match.length
will provide you with the number of matches. 然后,
match.length
将为您提供匹配数。 And to extract the matches, use indexes such as match[1]
match[2]
match[3]
... 要提取匹配项,请使用
match[1]
match[2]
match[3]
等索引...
You need to use the global flag, and multiline if you have new lines in there, and continually exec
the result until you have all your results in an array: 如果你有新行,你需要使用全局标志和多行,并且不断
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);
For reference check out this mdn article on exec
如需参考,请查看关于
exec
这篇mdn文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.