Regular expression for custom Time string

I made an android program allowing the user to enter a custom “time” string, for example:

  • 3h” (meaning 3 hours)
  • 2m30s” (meaning 2 minutes and 30 seconds)
  • 2h962s” (meaning 2 hours and 962 seconds (sic))
  • 1h5s6c” (meaning 1 hour, 5 seconds and 6 hundredths of a second)
  • 5h78m228c” (meaning 5 hours, 78 minutes (sic) and 228 hundredths of a second (sic))

I’ve been using this regular expression to validate that custom time string: ^([0-9]?[0-9]h)?([0-9]+m)?([0-9]+s)?([0-9]+c)?$ (therefore allowing a max of 99 hours, and unlimited number of minutes, seconds and hundredths of a second)

The problem is that I’d like to make optional the last unit, in order to make the program silently using the following unit. In the above examples, the user would be allowed to enter these strings instead of the above:

  • 3” (not specifying “h”, in order to make the program treat “3” as “3 hours”)
  • 2m30” (not specifying “s”, in order to make the program treat “30” as “30 seconds”)
  • 2h962s” (same, because without specifying “s” the program would treat “962” as “962 minutes”)
  • 1h5s6” (not specifying “c”, in order to make the program treat “6” as “6 hundredths of a second”)
  • 5h78m228c” (same, because without specifying “c” the program would treat “228” as “228 seconds”)

Which regular expression would I have then to use ?

Thanks

Answer

Check this one:

^([0-9]?[0-9](h|$))?([0-9]+(m|$))?([0-9]+(s|$))?([0-9]+(c|$))?$

Every time you check for a time unit, alternatively allow the end of a string.

Leave a Reply

Your email address will not be published. Required fields are marked *