re = /^No (?<no>\d{1,3}) (?<title>(?:[^(\r\n]+|\((?!\d\)))+)(?:\((?<weeks>\d)\))?/m
str = 'No 1 And Your Bird Can Sing (4)
No 2 Baby, You\'re a Rich Man (5)
No 3 Blue Jay Way S
No 4 Everybody\'s Got Something to Hide Except Me and My Monkey (1)'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html