使用正则表达式获取括号内的字符串,删除括号 [英] Get string inside parentheses, removing parentheses, with regex
问题描述
我有这两个字符串...
I have these two strings...
var str1 = "this is (1) test";
var str2 = "this is (2) test";
并且想要编写一个RegEx来提取括号内的内容,如"1"
和"2"
一样,以产生如下所示的字符串.
And want to write a RegEx to extract what is INSIDE the parentheses as in "1"
and "2"
to produce a string like below.
var str3 = "12";
现在我有这个正则表达式,它也返回括号...
right now I have this regex which is returning the parentheses too...
var re = (/\((.*?)\)/g);
var str1 = str1.match(/\((.*?)\)/g);
var str2 = str2.match(/\((.*?)\)/g);
var str3 = str1+str2; //produces "(1)(2)"
推荐答案
类似
JavaScript
Javascript
var str1 = "this is (1) test",
str2 = "this is (2) test",
str3 = str1.match(/\((.*?)\)/)[1] + str2.match(/\((.*?)\)/)[1];
alert(str3);
在 jsfiddle
请参见 (x)匹配x并记住匹配.这些称为捕获括号.
(x) Matches x and remembers the match. These are called capturing
parentheses. 例如,/(foo)/匹配并记住"foo bar"中的"foo".这可以从结果数组的元素中调用匹配的子字符串 1 ,...,[n]或来自预定义的RegExp对象的属性$ 1,...,9美元. For example, /(foo)/ matches and remembers 'foo' in "foo bar." The
matched substring can be recalled from the resulting array's elements
1, ..., [n] or from the predefined RegExp object's properties $1,
..., $9. 捕获组的性能会受到影响.如果您不需要要调用的匹配子字符串,更喜欢使用非捕获括号(请参见下文). Capturing groups have a performance penalty. If you don't need the
matched substring to be recalled, prefer non-capturing parentheses
(see below). 这篇关于使用正则表达式获取括号内的字符串,删除括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!