0

I need to convert a string containing a special time format to a standard one, example: "1h2m3s40ms" -> "01:02:03:0040". The source string could contain any combination of hours, minutes, seconds or milliseconds, like "1h4s", "34m", "23h45s" etc. And this is where I need some help.

A basic regular expression that would validate the string where they all have a value is pretty easy, like this:

"[0-9]+h[0-9]+m[0-9]+s[0-9]+ms"

But how do you make the individual hours, minutes etc optional?

I tried something like this:

"([0-9]+h)?([0-9]+m)?([0-9]+s)?([0-9]+ms)?"

But that didn't pass my regexp tester, everything was permitted.

Please help a regexp noob :)

robertpaulsen
  • 209
  • 4
  • 9
  • 1
    Try `^(?=\S)(?:([0-9]+)h)?(?:([0-9]+)m)?(?:([0-9]+)s)?(?:([0-9]+)ms)?$` ([demo](https://regex101.com/r/rNf1WJ/1)) – Wiktor Stribiżew Mar 08 '19 at 14:12
  • 1
    Your regex works fine : https://regex101.com/r/3d2OUS/2 (after adding the string start and end delimiters). You might need to check for the empty string, though. – Seblor Mar 08 '19 at 14:13

1 Answers1

0

Thanks for the quick answer, Seblor and Wiktor!

Yes, adding the string start and end delimiters did the trick:

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

robertpaulsen
  • 209
  • 4
  • 9