admin管理员组

文章数量:1331927

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.

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

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.

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)"
Share Improve this question edited Feb 20, 2019 at 19:08 isherwood 61.1k16 gold badges121 silver badges169 bronze badges asked Sep 1, 2013 at 15:12 user2415131user2415131 953 silver badges9 bronze badges 1
  • possible duplicate of How do you access the matched groups in a javascript regex? – Barmar Commented Sep 1, 2013 at 15:15
Add a ment  | 

3 Answers 3

Reset to default 5

Like this

Javascript

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

alert(str3);

On jsfiddle

See MDN RegExp

(x) Matches x and remembers the match. These are called capturing parentheses.

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

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"

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.?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.

EDIT 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);

本文标签: