13.07.2015 Views

Download - The Bastards Book of Regular Expressions

Download - The Bastards Book of Regular Expressions

Download - The Bastards Book of Regular Expressions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Capture, Reuse 86ApplesOraclesOrangesOre<strong>The</strong> most important letter is the left-most one: A comes before O in the alphabet, so all words thatbegin with A will come before any word that starts with O. But what if the words start with the sameletter? <strong>The</strong>n you compare the second letters, and so forth.This is the same with dates. In the American human-readable format, 03-09-2001 would comebefore 05-22-1978, as 03 comes earlier in the numerical scale than does 05. But chronologically, <strong>of</strong>course, 05-22-1978 is several decades before 03-09-2001. In the programmer-friendly version, the“biggest” parts <strong>of</strong> the date come first, i.e. the year, then the month and day. This makes sorting easy,because the alphabetical-order <strong>of</strong> the date text is the same as the chronological order <strong>of</strong> the actualdates.So, given the human readable version <strong>of</strong> the dates, write a regex that converts them to theprogrammer friendly version.AnswerFind (\d+)-(\d+)-(\d+)Replace $3-$1-$2Exercise: Zero-pad the dates<strong>The</strong> above exercise isn’t completely realistic, however, because the human-readable dates are usuallywritten in a more shorthand way:3-9-200111-14-20125-22-1978<strong>The</strong> month <strong>of</strong> March, in other words, is written simply as 3, not as 03Why is that extra zero there? If you think <strong>of</strong> the computer-sortable scenario, those extra zeros arevital. Consider the issue <strong>of</strong> two dates with the same year. In human readable format:11-20-20023-20-2002In machine-readable format:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!