15

I want to extract the text between the last () using javascript

For example

var someText="don't extract(value_a) but extract(value_b)";
alert(someText.match(regex));

The result should be

value_b

Thanks for the help

bobble bubble
  • 11,625
  • 2
  • 24
  • 38
user1376366
  • 161
  • 2
  • 2
  • 6

4 Answers4

20

Try this

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

See it here on regexr

var someText="don't extract(value_a) but extract(value_b)";
alert(someText.match(/\(([^)]*)\)[^(]*$/)[1]);

The part inside the brackets is stored in capture group 1, therefor you need to use match()[1] to access the result.

stema
  • 85,585
  • 19
  • 101
  • 125
8

An efficient solution is to let .* eat up everything before the last (

var str = "don't extract(value_a) but extract(value_b)";

var res = str.match(/.*\(([^)]+)\)/)[1];

console.log(res);

Here is a demo at regex101

bobble bubble
  • 11,625
  • 2
  • 24
  • 38
7
/\([^()]+\)(?=[^()]*$)/

The lookahead, (?=[^()]*$), asserts that there are no more parentheses before the end of the input.

Alan Moore
  • 71,299
  • 12
  • 93
  • 154
0

If the last closing bracket is always at the end of the sentence, you can use Jonathans answer. Otherwise something like this might work:

/\((\w+)\)(?:(?!\(\w+\)).)*$/
Avaq
  • 2,899
  • 1
  • 19
  • 25