CodexBloom - Programming Q&A Platform

Regex Not Recognizing Date Formats with Mixed Separators in Ruby - advanced patterns on Edge Cases

πŸ‘€ Views: 362 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
regex ruby string-manipulation Ruby

I'm trying to validate and extract dates from a text string in Ruby using regex, but I'm running into issues when the date formats use mixed separators. For example, my regex works with dates like `2023-10-05`, but fails when the date has a mix of separators like `2023/10.05` or `2023.10-05`. Here's the regex I've been using: ```ruby date_regex = /\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b/ # Matches YYYY-MM-DD or YYYY/MM/DD ``` I've tested it with several strings, but the mixed separators make it break. For instance, the string `"Today's date is 2023.10-05, let's check it."` returns no matches, which is unexpected. I've looked into using a more flexible regex pattern, but I'm unsure how to incorporate optional separators effectively without making it overly complex. Here’s the additional code snippet where I apply the regex: ```ruby text = "Today's date is 2023.10-05, let's check it." matches = text.scan(date_regex) puts matches.inspect # Should print the matched dates ``` The output is `[]`, meaning no matches were found. I really want to handle these edge cases without complicating things too much. Can anyone suggest a regex pattern that will correctly match dates regardless of whether the separators are mixed? I’d also appreciate tips on maintaining performance when dealing with large strings, as I plan to use this in a larger text processing application running on Ruby 3.1.0. How would you solve this?