There are a few ways of accomplishing your task, depending on what you want from the result. There's yours, where everything is jammed into one regex; this is ideal if you don't need anything beyond that (say, to capture the individual pieces, or easily associate something with which pattern matched). For just pulling dates out, it typically works.
However, when matching multiple possible patterns I tend to go with an incremental parser. You define all of your patterns, and organize them such that the more exact match first. For example, with your data set:
my $month_abv = qr/[[:upper:]][[:lower:]]{2}/; my @date_patterns = ( # Mar 11 2011 08:02:08.32 ['Mmm DD YYYY HH:MM:SS.uu', qr/$month_abv \s+ \d\d? \s+ \d{4} \s+ \d\d:\d\d:\d\d\.\d\d /x], # Mar 11 2011 08:02:08 ['Mmm DD YYYY HH:MM:SS', qr/$month_abv \s+ \d\d? \s+ \d{4} \s+ \d\d:\d\d:\d\d /x], # Mar 11 08:02:08.32 ['Mmm DD HH:MM:SS.uu', qr/$month_abv \s+ \d\d? \s+ \d\d:\d\d:\d\d\.\d\d /x], # Mar 11 08:02:08 ['Mmm DD HH:MM:SS', qr/$month_abv \s+ \d\d? \s+ \d\d:\d\d:\d\d /x], ); my $line = q{ Mar 11 08:02:08 172.28.17.253 Mar 11 2011 08:02:08 D+R-FW-1 : Jan 1 2011 00:00:00.07; }; DATE: until ($line =~ /\G\z/gc) { foreach my $pat (@date_patterns) { my($form, $re) = @$pat; if ($line =~ /\G\b($re)\b/gc) { say "Matching date form '$form': $1"; next DATE; } } $line =~ /./sgc; # no matches, bumpalong }
Each of your possible patterns are defined (in length order, so that the smaller patterns are tried last). You get free metadata with it; in this case, a simple string that describes the pattern. In more complicated cases you'd want a function that reformats the date, or shoves it into an object, etc. based on captures within the pattern.
Incidentally, while I did change your [A-Z] and [a-z] to something a little more locale friendly ([[:upper:]] and [[:lower:]]), what the month pattern really should be is simply \w+, or perhaps [[:alpha:]]. For your data set it probably doesn't matter, but not all languages provide three characters for the month, or provide it with the first letter uppercased. Some locales may not even use all letters for month names. The rest of the pattern in each case should filter out false positives.
In addition to changing the metadata, you could change the \b delimiters; perhaps your dates are all before and after whitespace, or some punctuation. Making it specific to your data set can eliminate more false positives.
In order to accomplish this with one big regex you would simply join the regexes in @date_patterns with |, and commence matching as normal.
In reply to Re: regex for multiple dates
by Somni
in thread regex for multiple dates
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |