Alex F Alex F - 2 years ago 96
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:


=> "(some nonsense) and more words (target group)"

=> "(some nonsense) and more words (target group)"


=> "(some nonsense)"

=> "(some nonsense) and more words (target group)"

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

Answer Source

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

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

=> "(target group)"

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

=> "(target group)"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download