Get string inside parentheses, removing parentheses, with regex

后端 未结 3 1422
甜味超标
甜味超标 2020-12-11 22:03

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

3条回答
  •  北海茫月
    2020-12-11 22:34

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

提交回复
热议问题