Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This actually is something that regexes are good at; making an assumption, moving forward with it, then backtracking if necessary to get a successful match.</p> <pre><code>s{ \A ( 1[0-2] | 0?[1-9] ) [-/ ]? ( 3[01] | [12][0-9] | 0?[1-9] ) [-/ ]? ( (?: [0-9]{2} ){1,2} ) \z } { sprintf '%02u/%02u/%04u', $1, $2, ( length $3 == 4 ? $3 : 2000+$3 ) }xe; </code></pre> <p>The range checks present, while not determined by the value of the month, should be sufficient to pick a good date from the ambiguous cases (where there is a good date).</p> <p>Note that it is important to try two digit month and days first; otherwise 111111 becomes 1-1-1111, not the presumably intended 11-11-11. But this means 11111 will prefer to be 11-1-11, not 1-11-11.</p> <p>If a valid day of month check is needed, it should be performed after reformatting.</p> <p>Notes:</p> <p><code>s{}{}</code> is a substitution using curly braces instead of / to delimit the parts of the regex to avoid having to escape the /, and also because using paired delimiters allows opening and closing both the pattern and replacement parts, which looks nice to me.</p> <p><code>\A</code> matches the start of the string being matched; <code>\z</code> matches the end. <code>^</code> and <code>$</code> are often used for this, but can have slightly different meanings in some cases; I prefer these since they always only mean one thing.</p> <p>The x flag on the end says this is an extended regex that can have extra whitespace or comments that are ignored, so that it is more readable. (Whitespace inside a character class isn't ignored.) The e flag says the replacement part isn't a string, it is code to execute.</p> <p><code>'%02u/%02u/%02u'</code> is a printf format, used for taking values and formatting them in a particular way; see <a href="http://perldoc.perl.org/functions/sprintf.html" rel="nofollow">http://perldoc.perl.org/functions/sprintf.html</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload