re = /^(?<year>\d{4})[-\/](?<month>0[1-9]|1[0-2])[-\/](?<day>0[1-9]|[1-2][0-9]|3[0-1])(?:[T\s](?:(?<hour>0[0-9]|1[0-9]|2[0-4]):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<nano>\d+))?))?(?:(?<offset>[Zz]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)$/m
str = '2020-12-01T12:13:51.123+02:00
2020-12-01T12:13:51.123+0200
2020-12-01T12:13:51.123Z
2020-12-01T12:13:51.123
2020-12-01T12:13:51.123341512+02:00
2020-12-01T12:13:51.123341512+0200
2020-12-01T12:13:51.123341512Z
2020-12-01T12:13:51.123341512
2020-12-01T12:13:51+02:00
2020-12-01T12:13:51+0200
2020-12-01T12:13:51Z
2020-12-01T12:13:51
2020-12-01 12:13:51.123 +02:00
2020-12-01 12:13:51.123 +0200
2020-12-01 12:13:51.123Z
2020-12-01 12:13:51.123
2020-12-01 12:13:51.123341512 +02:00
2020-12-01 12:13:51.123341512 +0200
2020-12-01 12:13:51.123341512Z
2020-12-01 12:13:51.123341512
2020-12-01 12:13:51+02:00
2020-12-01 12:13:51+0200
2020-12-01 12:13:51Z
2020-12-01 12:13:51
2020-12-01+02:00
2020-12-01+0200
2020-12-01Z
2020-12-01
2020/12/01T12:13:51.123+02:00
2020/12/01T12:13:51.123+0200
2020/12/01T12:13:51.123Z
2020/12/01T12:13:51.123
2020/12/01T12:13:51.123341512+02:00
2020/12/01T12:13:51.123341512+0200
2020/12/01T12:13:51.123341512Z
2020/12/01T12:13:51.123341512
2020/12/01T12:13:51+02:00
2020/12/01T12:13:51+0200
2020/12/01T12:13:51Z
2020/12/01T12:13:51
2020/12/01+02:00
2020/12/01+0200
2020/12/01Z
2020/12/01
2039/15/23
2923/09/12
2023/23/51
2020-12-01T00:13:51
2020-12-01T01:13:51
2020-12-01T10:13:51
2020-12-01T19:13:51
2020-12-01T20:13:51
2020-12-01T24:13:51'
subst = '$1-$2-$3'
result = str.gsub(re, subst)
# Print the result of the substitution
puts result
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