1

I am having trouble finding any regex which actually matches what I need, despite how easy this request seemed when I started out. Hoping to get help here.

An early mistake in our code is sending dates in the format YYYY-MM-DD HH:mm:ss:SSS. This is not valid ISO, as the milliseconds are proceeded by a colon, not a period.

I wanted a quick regex to use in conjunction with JS .replace() to match the third colon : and replace it with a period . As I said, this sounded pretty basic -- but I have found nothing that works, and no other places where the suggested fix for a similar problem has worked in my case.

Any help is appreciated.

DrHall
  • 719
  • 1
  • 7
  • 23

1 Answers1

4

You can use /^((?:[^:]*:){2}[^:]*):(.*)$/; (?:[^:]*:){2} matches up to the second colon and ^((?:[^:]*:){2}[^:]*) matches the string from the beginning of the string until the third colon; (.*)$ matches everything after the third colon; Capture what is before the third colon and what is after, reformat the string with back reference:

console.log("YYYY-MM-DD HH:mm:ss:SSS".replace(/^((?:[^:]*:){2}[^:]*):(.*)$/, "$1.$2"))

Or a simpler one for this specific case, replace the last colon with .:

console.log("YYYY-MM-DD HH:mm:ss:SSS".replace(/:(?=[^:]*$)/, "."))
Psidom
  • 209,562
  • 33
  • 339
  • 356