CodexBloom - Programming Q&A Platform

Regex Not Extracting ISO 8601 Date Strings from Mixed Text in JavaScript

👀 Views: 58 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex javascript date JavaScript

I'm prototyping a solution and I tried several approaches but none seem to work. I'm trying to extract ISO 8601 date strings (like `2023-10-15T12:30:00Z`) from a mixed text input using regex in JavaScript, but I'm running into issues where not all of my valid date strings are getting captured. I've written the following regex pattern: ```javascript const regex = /(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})?)/g; ``` I used this regex on a sample text: ```javascript const text = 'The event starts on 2023-10-15T12:30:00Z and ends on 2023-10-16T14:00:00+02:00, but there might also be updates on 2023-10-15 12:30:00.'; const matches = text.match(regex); console.log(matches); ``` However, when I run this, I only get the first two matches, and I'm not sure why the third date (`2023-10-15 12:30:00`) is not captured. It seems to ignore dates that do not have the `T` separator. I've also tried various configurations of the regex, including optional groups and non-capturing groups, but nothing seems to work. Is there a way to modify this regex to include both formats of the date strings? Should I be using a different regex altogether? Any insights would be appreciated! I'm working on a web app that needs to handle this. Thanks in advance! I'm working in a Ubuntu 22.04 environment. Could someone point me to the right documentation?