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?
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.)
string.scan(regex).present? is more concisely written as
string =~ regex.