[Regex] Get LAST match

learning-elixir
#1

I thought i would ask here, as I seem to be getting good info here, and this is for an elixir/phoenix project…

i am getting back data that looks like:

Band Name (4)

where 4 is the number of plays on the station…

i am currently doing:

~r/(.*?)\s*\((.*?)\)/

to pull out the artist and play counts…

But i recently got a few entries that look like:

Band Name(c) (4)

and it chokes my regex…

Can I write this so it only breaks off at the LAST match of “()”.

Thanks in advance…

#2

You can just get last match ~r/\([^)]*\)/ |> Regex.scan(string) |> List.last()

1 Like
#3

This regular expression does the right thing for your example:

^(.*?)\s*\((?!.*\()(.*?)\)$

It adds the expression (?!.*\(), which is a negative lookahead looking for any more \( before $