265

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 "(" and ")"

I expect five hundred dollars ($500).

would return

$500

Found Regular expression to get a string between two strings in Javascript

I don't know how to use '(', ')' in regexp.

starball
  • 20,030
  • 7
  • 43
  • 238
Okky
  • 10,338
  • 15
  • 75
  • 122
  • possible duplicate of [Regular Expression to find a string included between two characters, while EXCLUDING the delimiters](http://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclu) – Ro Yo Mi Jul 22 '13 at 04:27
  • you can use go-oleg's solution below, slightly modified to test for the dollar sign: `var regExp = /\(\$([^)]+)\)/;` – Dom Day Jul 22 '13 at 04:44
  • Would be nice to see what you've tried so far. – Scipion Sep 03 '20 at 09:22

10 Answers10

627

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

user1063287
  • 10,265
  • 25
  • 122
  • 218
go-oleg
  • 19,272
  • 3
  • 43
  • 44
  • 18
    +1 Nice, worked like a charm. I would like to add you to add this http://tinyurl.com/mog7lr3 in your for a visual explanation. – Praveen Sep 26 '13 at 06:59
  • What if i require to retrieve between [something] – CodeGuru Jul 29 '14 at 10:37
  • 8
    This doesn't work if there are parentheses within the parentheses you want to capture. Such as: "I expect five hundred dollars ($500 (but I know I'll never see that money again))." – JayB May 11 '15 at 15:57
  • hi i tried getting regex for retuning a value between `-` example `2015-07-023` i want to get `07` i tried `var regExp = /\(([^)]+-)\)/;` but i get null can your clarify? – Brownman Revival Jul 16 '15 at 05:18
  • `("(some txt )".match(/\(([^)]+)\)/g)[1] === undefined);`. Please clarify. – Cody Oct 11 '15 at 23:22
  • 6
    This regex works only if matching one instance per sting. Using the global `/g` flag wont work as expected. – silkAdmin Dec 26 '15 at 04:01
  • if brackets are changed into double quotes, e.g. "$500", it becomes `/\"([^)]+)\"/` Yes! I did it! thnks. – Joe Kdw Feb 03 '16 at 04:42
  • Why isn't it the first match? i.e. matches[0] – Ian Warburton Apr 28 '16 at 23:50
  • 2
    @IanWarburton, matches[0] gives you the full string of characters matched '($500)', while matches[1] gives you just what's in the capturing group. Here is some more info on the return value of regExp.match(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec – sbru Sep 09 '16 at 16:15
  • 9
    what is the solution if you have multiple strings inside parentheses like below: "I expect (five) hundred dollars ($500)" let's say I want an array of those special strings. – Mohamad Al Asmar Jan 04 '18 at 15:11
  • @CodeGuru To retrieve between [something] use the regex `/\[(.*?)\]/` – rudrasiva86 May 26 '18 at 18:54
  • why /\(.*\)/ not working? and you need that addition of 'capturing group'? – nadavgam Jan 15 '20 at 10:29
  • This is really useful, having access to the full statement, with the brackets, in `matches[0]` and the actual value in `matches[1]` as it means that I can deal with and process `matches[1]` and then remove `matches[0]` from my original string with such a statement as `myString.replace(matches[0], "");` – Mike Irving Feb 14 '20 at 09:46
  • how to store this regex as string literal in data store and use it again ? If I do, `regex = new RegExp("/\(([^)]+)\)/", "ig")` it's not working – Kamalakannan J Aug 30 '21 at 08:37
  • Can this be modified to retain the parentheses in each match? In other words: `matches[0] === '($500)'`? UPDATE—FIGURED IT OUT: just capture the group outside the term: `/(\([^)]+\))/g` – sambecker Sep 21 '21 at 19:33
42

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));
}
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
25

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)

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
  • 2
    add optional chaining in case match doesnt exist will return undefined instead of resulting in uncaught exception ("I expect five hundred dollars ($500).").match(/\((.*)\)/)?.pop(); – dano May 18 '22 at 18:39
21

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));
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
13

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]
  })
Community
  • 1
  • 1
silkAdmin
  • 4,640
  • 10
  • 52
  • 83
  • 1
    What I was looking for. https://stackoverflow.com/questions/49614116/how-to-get-all-sub-strings-inside-a-string-that-starts-with-and-end-with-a-chara?noredirect=1#comment86234810_49614116 – wobsoriano Apr 02 '18 at 15:40
8

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

marcofriso
  • 119
  • 1
  • 5
6

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

Or \(.+\) for anything inside brackets

P0W
  • 46,614
  • 9
  • 72
  • 119
  • 3
    This will work for the sample text, however if another `)` appears later in the string like `I expect five hundred dollars ($500). (but I'm going to pay).` the greediness of the `+` will capture a lot more. – Ro Yo Mi Jul 22 '13 at 04:25
  • 1
    @Denomales So how would you have it capture both instances of those strings. Ideally I am doing something similar but I would like to have: `($500)` and `(but I'm going to pay)` be matched but in two separates matches rather than being considered a single matched item? Thanks in advance! – Tom Bird Jun 16 '15 at 01:26
  • 1
    \(.+\) worked for my requirement. Needed to capture stuffs like "Dunhill (Bottle/Packet/Pot/Shot)" and return just "Dunhill" – Ojchris Jul 23 '19 at 17:14
4

let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');
console.log(str) // Inside brackets
Andran
  • 299
  • 1
  • 7
2
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

AJ Dhaliwal
  • 661
  • 1
  • 8
  • 24
0

Simple: (?<value>(?<=\().*(?=\)))

I hope I've helped.