Regular Expression to get a string between parentheses in Javascript

后端 未结 9 798
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 09:45

I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings \"(\"

9条回答
  •  醉话见心
    2020-11-22 10:21

    var str = "I expect five hundred dollars ($500) ($1).";
    var rex = /\$\d+(?=\))/;
    alert(rex.exec(str));
    

    Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.

    var str = "I expect five hundred dollars ($500) ($1).";
    var rex = /\$\d+(?=\))/g;
    var matches = str.match(rex);
    for (var i = 0; i < matches.length; i++)
    {
        alert(matches[i]);
    }
    

    This code alerts with all the matches.

    References:

    search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp

    search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

提交回复
热议问题