简体   繁体   中英

Regex for getting text between the last brackets ()

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

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.

/\([^()]+\)(?=[^()]*$)/

前瞻(?=[^()]*$)断言在输入结束之前没有更多的括号。

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

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+\)).)*$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM