Reputation: 95
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)"
Upvotes: 4
Views: 7113
Reputation: 2747
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);
Upvotes: 0
Reputation: 23502
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).
Upvotes: 5
Reputation: 15933
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"
Upvotes: 0