Regular Expression to get a string between parentheses in Javascript

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

提交回复
热议问题