search

Home  >  Q&A  >  body text

javascript - How to get the content in parentheses using regular expressions in js?

var str="deleteChild(236737)";
For example, get the number in parentheses 236737 Others are not required.
How to write regular js.
js array is too troublesome. Because the number in the parentheses will change.

滿天的星座滿天的星座2754 days ago695

reply all(6)I'll reply

  • 某草草

    某草草2017-05-19 10:42:53

    Use d+ to indicate any whole number. In order to match the content at a special location, the concept of group in regular expressions is also used (shown in regular expressions as being enclosed by a pair of parentheses).

    The shortcut way of expressing JavaScript regular expression is to enclose it with "/", for example /正则表达式内容/, it has an exec method, and the incoming parameter is the string to be checked.
    The execution result of the exec method returns an array or null value (when there is no content in str that matches the regular expression).

    If the regular expression contains group and the content is matched, then in the returned result array, the text content represented by group will appear in the second array element and subsequent array elements of the result array (when the regular expression contains When containing multiple groups).

    var str = "deleteChild(236737)";
    var result = /\((\d+)\)/.exec(str);
    
    if(result.length > 1) {  //加这个判断是以防字符串中没有匹配的内容,那么result[1]会抛错!
       console.log("您想要的结果是:" +result[1]); //输出 236737。 
    } else {
       console.log("字符串中没有符合条件的数字");
    }

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:42:53

    var number = "deleteChild(236737)".replace(/.*\((\d+)\)$/, '$1');

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:42:53

    You can use the split method of string. split() 方法用于把一个字符串分割成字符串数组。

    var num1=str.split("(")  //["deleteChild", "236737)"]
    var num2=num1[1].split(")") //["236737", ""]
    var result=num[0]

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:42:53

    My answer is also based on the principle of high-voted answers, but I personally think it may be easier to understand if I write it this way

    var str = "deleteChild(236737)";
    var reg= /\((\d+)\)/;
    
    if(reg.test(str)){ //如果匹配上直接获取括号里的内容
        console.log(RegExp.) //236737
    }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:42:53

    /\d+/g

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:42:53

    I agree with the writing method on the 4th floor, it is so simple and convenient.
    Systematic learning of regular expressions, I highly recommend the regular expression front-end user manual | louis blog
    sf link: Regular expression front-end user manual-Louis chats about the front-end-SegmentFault
    The original content is super long , a very comprehensive summary.

    reply
    0
  • Cancelreply