re = /^(P((?<numYears>[1-9]+[0-9]*)Y)?((?<numMonths>[1-9]+[0-9]*)M)?((?<numDays>[1-9]+[0-9]*)D)?(T((?<numHours>[1-9]+[0-9]*)H)?((?<numMinutes>[1-9]+[0-9]*)M)?((?<numSeconds>[1-9]+[0-9]*)S)?)?|P(?<numWeeks>[1-9]+[0-9]*)W)$/m
str = 'P1Y2M3DT4H5M6S
P1M
PT1M
P1MT1M
P1W
P1D
PT2S
'
# 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