简体   繁体   English

使用正则表达式获取括号内的字符串,删除括号

[英]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";

And want to write a RegEx to extract what is INSIDE the parentheses as in "1" and "2" to produce a string like below. 并且想要编写一个RegEx来提取INSIDE括号中的内容,如"1""2"以生成如下所示的字符串。

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)"

Like this 像这样

Javascript 使用Javascript

var str1 = "this is (1) test",
    str2 = "this is (2) test",
    str3 = str1.match(/\((.*?)\)/)[1] + str2.match(/\((.*?)\)/)[1];

alert(str3);

On jsfiddle jsfiddle

See MDN RegExp 请参阅MDN RegExp

(x) Matches x and remembers the match. (x)匹配x并记住匹配。 These are called capturing parentheses. 这些被称为捕获括号。

For example, /(foo)/ matches and remembers 'foo' in "foo bar." 例如,/(foo)/匹配并记住“foo bar”中的'foo'。 The matched substring can be recalled from the resulting array's elements 1 , ..., [n] or from the predefined RegExp object's properties $1, ..., $9. 可以从结果数组的元素1 ,...,[n]或预定义的RegExp对象的属性$ 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). 如果您不需要调用匹配的子字符串,则更喜欢非捕获括号(参见下文)。

Try: 尝试:

/[a-zA-Z0-9\s]+\((\d+)\)[a-zA-Z0-9\s]+/

This will capture any digit of one or more inside the parentheses. 这将捕获括号内的一个或多个数字。

Example: http://regexr.com?365uj 示例: http//regexr.com?365uj

EDIT: In the example you will see the replace field has only the numbers, and not the parentheses--this is because the capturing group $1 is only capturing the digits themselves. 编辑:在示例中,您将看到替换字段只有数字,而不是括号 - 这是因为捕获组$1仅捕获数字本身。

EDIT 2: 编辑2:

Try something like this: 尝试这样的事情:

var str1 = "this is (1) test";
var str2 = "this is (2) test";

var re = /[a-zA-Z0-9\s]+\((\d+)\)[a-zA-Z0-9\s]+/;

str1 = str1.replace(re, "$1");
str2 = str2.replace(re, "$1");

console.log(str1, str2);

try this 试试这个

    var re = (/\((.*?)\)/g);

    var str1 = str1.match(/\((.*?)\)/g);
    var new_str1=str1.substr(1,str1.length-1);
    var str2 = str2.match(/\((.*?)\)/g);
    var new_str2=str2.substr(1,str2.length-1);

    var str3 = new_str1+new_str2; //produces "12"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM