4

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)"
isherwood
  • 52,576
  • 15
  • 105
  • 143
user2415131
  • 95
  • 3
  • 8
  • possible duplicate of [How do you access the matched groups in a javascript regex?](http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regex) – Barmar Sep 01 '13 at 15:15

3 Answers3

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

Xotic750
  • 21,928
  • 8
  • 53
  • 76
0

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

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);
honyovk
  • 2,669
  • 17
  • 26
0

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"
Tushar
  • 13,804
  • 1
  • 24
  • 44