我有这两个弦...
var str1 = "this is (1) test";
var str2 = "this is (2) test";
并希望编写一个RegEx来提取括号内的内容,"1"
并"2"
生成如下所示的字符串。
var str3 = "12";
现在我有这个正则表达式也返回括号...
var re = (/\((.*?)\)/g);
var str1 = str1.match(/\((.*?)\)/g);
var str2 = str2.match(/\((.*?)\)/g);
var str3 = str1+str2; //produces "(1)(2)"
像这样
Java脚本
var str1 = "this is (1) test",
str2 = "this is (2) test",
str3 = str1.match(/\((.*?)\)/)[1] + str2.match(/\((.*?)\)/)[1];
alert(str3);
在 jsfiddle
请参阅MDN RegExp
(x)匹配x并记住匹配。这些称为捕获括号。
例如,/(foo)/匹配并记住“ foo bar”中的“ foo”。可以从结果数组的元素1,...,[n]或预定义的RegExp对象的属性$ 1,...,$ 9中调用匹配的子字符串。
捕获组会产生性能损失。如果不需要调出匹配的子字符串,请使用非捕获括号(请参见下文)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句