[英]How to read all string inside parentheses using regex
I wanted to get all strings inside a parentheses pair. 我想将所有字符串放在括号对中。 for example, after applying regex on
例如,在
"fun('xyz'); fun('abcd'); fun('abcd.ef') { temp('no'); "
output should be 输出应该是
['xyz','abcd', 'abcd.ef'].
I tried many option but was not able to get desired result. 我尝试了很多选择,但未能获得理想的结果。 one option is
一种选择是
/fun\\((.*?)\\)/gi.exec("fun('xyz'); fun('abcd'); fun('abcd.ef')")
. /fun\\((.*?)\\)/gi.exec("fun('xyz'); fun('abcd'); fun('abcd.ef')")
。
Store the regex in a variable, and run it in a loop... 将正则表达式存储在变量中,然后循环运行...
var re = /fun\((.*?)\)/gi,
string = "fun('xyz'); fun('abcd'); fun('abcd.ef')",
matches = [],
match;
while(match = re.exec(string))
matches.push(match[1]);
Note that this only works for global regex. 请注意,这仅适用于全局正则表达式。 If you omit the
g
, you'll have an infinite loop. 如果省略
g
,则会有一个无限循环。
Also note that it'll give an undesired result if there a )
between the quotation marks. 还请注意,如果引号之间有
)
,则会产生不希望的结果。
You can use this code will almost do the job: 您可以使用以下代码几乎完成这项工作:
"fun('xyz'); fun('abcd'); fun('abcd.ef')".match(/'.*?'/gi);
You'll get ["'xyz'", "'abcd'", "'abcd.ef'"]
which contains extra '
around the string. 您将获得
["'xyz'", "'abcd'", "'abcd.ef'"]
,该字符串周围包含额外的'
。
The easiest way to find what you need is to use this RegExp: /[\\w.]+(?=')/g
查找所需内容的最简单方法是使用此RegExp:/[
/[\\w.]+(?=')/g
var string = "fun('xyz'); fun('abcd'); fun('abcd.ef')";
string.match(/[\w.]+(?=')/g); // ['xyz','abcd', 'abcd.ef']
It will work with alphanumeric characters and point, you will need to change [\\w.]+
to add more symbols. 它可以使用字母数字字符和点,您需要更改
[\\w.]+
以添加更多符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.