learningruby347 learningruby347 - 5 months ago 15x
Ruby Question

How to combine these two Ruby string tests in one regular expression?

I'm trying to write a regular expression in Ruby where I want to see if the string contains a certain word and has "stuff" between parenthesis.

Right now I'm doing:

string.include?("string") && string.scan(/\(([^\)]+)\)/).present?

Is there a way I can combine them using regular expressions? Thank you.


The most important improvement you can make is to also test that the word and the parentheseses have the correct relationship. If I understand correctly, "link(url link_name)" should be a match but "(url link_name)link" or "link stuff (url link_name)" should not. So match "link", the parentheses, and their contents, and capture the contents, all at once:

"stuff link(url link_name) more stuff".match(/link\((\S+?) (\S+?)\)/)&.captures
=> ["url", "link_name"]

(&. is Ruby 2.3; use Rails' .try :captures in older versions.)

Side note: string.scan(regex).present? is more concisely written as string =~ regex.