Match the last group inside _ () _ with the regex in Ruby

I need to extract the last occurrence of a substring enclosed in _()_, for example.

'a_long_(abc)_000' => abc
'a_long(string)_(def)_000' => def
'a_long_(string)_(abc)_blabla' => abc
+3
source share
4 answers

Match with /_\((.*?)\)_/and take the last match:

>> 'a_long_(string)_foo_(abc)_blabla'.scan(/_\((.*?)\)_/)[-1]
=> ["abc"]
+2
source

Smth like this:

str[/.*_\((.*?)\)_/,1]
+2
source

You can also use regex:

.*_\((.*?)\)_

Take a look

+1
source

It:

\(([^\)]+)\)_[a-zA-Z0-9]*$

$1 should be your string

0
source

Source: https://habr.com/ru/post/1785199/


All Articles