![]() |
|
XP is just a number | |
PerlMonks |
Re: regex for multiple datesby Somni (Friar) |
on Jul 06, 2011 at 23:43 UTC ( #913102=note: print w/replies, xml ) | Need Help?? |
Can't say I dig your regex all that much. Too many uses of unnecessary brackets, and an avoidance of more readable character classes. It's good you started with /x, but there is such thing as too much vertical whitespace.
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:
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 Section
Seekers of Perl Wisdom
|
|