Regular Expression to get a string between parentheses in Javascript

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

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

    Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.

    var matches = string2.split('[')
      .filter(function(v){ return v.indexOf(']') > -1})
      .map( function(value) { 
        return value.split(']')[0]
      })
    
    0 讨论(0)
  • 2020-11-22 10:22

    For just digits after a currency sign : \(.+\s*\d+\s*\) should work

    Or \(.+\) for anything inside brackets

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