Alex F Alex F - 6 months ago 18
Ruby Question

Ruby Regex to capture value only of the last matching group

I've got confused about using non-greedy regex in Ruby when the matching should be done from the end of the string.

Assuming that my string:

s = "Some words (some nonsense) and more words (target group)"


And I want to get "(target group)" in result. How can I do that? Was trying the following:

greedy:

s.match(/\(.*\)$/)[0]
=> "(some nonsense) and more words (target group)"

s.match(/\(.*\)/)[0]
=> "(some nonsense) and more words (target group)"


non-greedy:

s.match(/\(.*?\)/)[0]
=> "(some nonsense)"

s.match(/\(.*?\)$/)[0]
=> "(some nonsense) and more words (target group)"


Please note, that initial string may or may not include any number of groups in "()".

Answer

Not sure I understand your question. So my apologies if I get this wrong:

Are you sure you need .*? when [^)]* will do?

s.match(/\([^)]*\)$/)[0]
=> "(target group)"

If you insist on using .*? anyway, precede your reluctant match with a greedy match:

s.match(/^.*(\(.*?\))$/)[1]
=> "(target group)"
Comments