Get string inside parentheses, removing parentheses, with regex

后端 未结 3 1423
甜味超标
甜味超标 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);
    
    0 讨论(0)
  • 2020-12-11 22:47

    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"
    
    0 讨论(0)
  • 2020-12-11 22:52

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

    0 讨论(0)
提交回复
热议问题