Regex for getting text between the last brackets (

2020-02-01 18:08发布

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

4条回答
别忘想泡老子
2楼-- · 2020-02-01 18:51

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

查看更多
放我归山
3楼-- · 2020-02-01 18:55

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+\)).)*$/
查看更多
霸刀☆藐视天下
4楼-- · 2020-02-01 19:05

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.

查看更多
不美不萌又怎样
5楼-- · 2020-02-01 19:05
/\([^()]+\)(?=[^()]*$)/

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

查看更多
登录 后发表回答