CodexBloom - Programming Q&A Platform

Regex scenarios to Match Date Formats with Different Separators in Ruby

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-13
regex ruby date Ruby

Could someone explain I'm having trouble getting my regular expression to match various date formats in a string where the date can be separated by slashes, dashes, or dots. Specifically, I'm trying to capture dates formatted as `DD/MM/YYYY`, `DD-MM-YYYY`, or `DD.MM.YYYY`. I've written the following regex pattern in Ruby: ```ruby pattern = /\b(\d{2})[-/.](\d{2})[-/.](\d{4})\b/" ``` However, when I test it against a string like `"The event is on 23-05-2023 and the deadline is 15/06/2023 or 18.07.2023."`, it only matches the first date and seems to get confused with the separators. I tried using the global match option, but I'm still only getting the first match. Here's how I am executing the regex: ```ruby text = 'The event is on 23-05-2023 and the deadline is 15/06/2023 or 18.07.2023.' text.scan(pattern) do |day, month, year| puts "Matched date: #{day}/#{month}/#{year}" end ``` This outputs only `Matched date: 23/05/2023`, and I'm missing the other two dates. Is there something wrong with the regex pattern itself, or am I missing a specific option or adjustment in Ruby to capture all instances? I’d appreciate any help or insights into why the regex behaves this way, especially with different separators. I'm using Ruby 3.0.2. This is happening in both development and production on macOS.