re = /if\s+(\()?i\*{2}2\s*\+\s*j\*{2}2\s*==\s*k\*{2}2(?(1)\)|)\s*:/m
str = 'Sin paréntesis encaja:
if i**2+j**2==k**2:
Con paréntesis también:
if (i**2+j**2==k**2):
Con paréntesis no balanceados no encaja:
if i**2+j**2==k**2):
if (i**2+j**2==k**2:
'
# 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