Regular Expression to get a string between parentheses in Javascript

后端 未结 9 661
被撕碎了的回忆
被撕碎了的回忆 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:09

    let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');
    console.log(str) // Inside brackets

    0 讨论(0)
  • 2020-11-22 10:09

    Alternative:

    var str = "I expect five hundred dollars ($500) ($1).";
    str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
    
    → (2) ["$500", "$1"]
    

    It is possible to replace brackets with square or curly brackets if you need

    0 讨论(0)
  • 2020-11-22 10:12

    Try string manipulation:

    var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
    var newTxt = txt.split('(');
    for (var i = 1; i < newTxt.length; i++) {
        console.log(newTxt[i].split(')')[0]);
    }
    

    or regex (which is somewhat slow compare to the above)

    var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
    var regExp = /\(([^)]+)\)/g;
    var matches = txt.match(regExp);
    for (var i = 0; i < matches.length; i++) {
        var str = matches[i];
        console.log(str.substring(1, str.length - 1));
    }
    
    0 讨论(0)
  • 2020-11-22 10:12

    Simple solution

    Notice: this solution can be used for strings having only single "(" and ")" like string in this question.

    ("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();
    

    Online demo (jsfiddle)

    0 讨论(0)
  • 2020-11-22 10:18

    To match a substring inside parentheses excluding any inner parentheses you may use

    \(([^()]*)\)
    

    pattern. See the regex demo.

    In JavaScript, use it like

    var rx = /\(([^()]*)\)/g;
    

    Pattern details

    • \( - a ( char
    • ([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
    • \) - a ) char.

    To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.

    Most up-to-date JavaScript code demo (using matchAll):

    const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
    const rx = /\(([^()]*)\)/g;
    strs.forEach(x => {
      const matches = [...x.matchAll(rx)];
      console.log( Array.from(matches, m => m[0]) ); // All full match values
      console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
    });

    Legacy JavaScript code demo (ES5 compliant):

    var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
    var rx = /\(([^()]*)\)/g;
    
    
    for (var i=0;i<strs.length;i++) {
      console.log(strs[i]);
    
      // Grab Group 1 values:
      var res=[], m;
      while(m=rx.exec(strs[i])) {
        res.push(m[1]);
      }
      console.log("Group 1: ", res);
    
      // Grab whole values
      console.log("Whole matches: ", strs[i].match(rx));
    }

    0 讨论(0)
  • 2020-11-22 10:19

    You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

    var regExp = /\(([^)]+)\)/;
    var matches = regExp.exec("I expect five hundred dollars ($500).");
    
    //matches[1] contains the value between the parentheses
    console.log(matches[1]);

    Breakdown:

    • \( : match an opening parentheses
    • ( : begin capturing group
    • [^)]+: match one or more non ) characters
    • ) : end capturing group
    • \) : match closing parentheses

    Here is a visual explanation on RegExplained

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