re = /^(?<s1>\d)(?<n>[^~]*)(~(?<a1>\d*)?(~(?<s2>\d)~(?<a2>.+))?)?$/m
str = '142у~72~3~Г7
0~~1~1
542У~~1~2
142~1
142
'
# 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