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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Changing phone format (TODO)Todo: This was moved over from a different chapter. Need to rewrite introductory guff.Telephone gameIf you’ve ever signed up for something on the Internet, you’ve undoubtedly entered your phonenumber in an HTML form. And you’ve probably noticed that some forms are smarter than others.For example, some forms will automagically handle the formatting <strong>of</strong> the phone number. As youtype, it’ll insert dashes and parentheses so that it’s easy for you to read. Thus, typing in:5556667777Will show up in your web browser (through the magic <strong>of</strong> Javascript) as this:(555)-666-7777However, on less sophisticated websites, the web forms might tell you explicitly how the numbershould be formatted. For example, it might read “Please do not use dashes.” Or, “Please enter yournumber in XXX-YYY-ZZZZ” format. And if you don’t follow the instructions, the form rejects yoursubmission.Hopefully, you know enough about regexes to wonder: Why don’t they just use regexes to flexiblyadapt to what a user enters? And you would be right, in my opinion, to accuse them <strong>of</strong> lazyprogramming.But let’s not just sulk about it. Let’s see what the actual technical hurdle is in implementing anauto-formatting feature.We’ll start out with how to match the simplest form <strong>of</strong> a (standard U.S.) phone number. And thenwe’ll add more and more variation to the possible phone number formats and adjust our regex tobecome more inclusive.For each exercise, the goal is to convert any given phone number to the following format:(555)-666-7777Exercise: A solid line <strong>of</strong> digits <strong>The</strong> simplest form <strong>of</strong> phone number is just 10-digits in a row, withno dashes or space in between them:136

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

Saved successfully!

Ooh no, something went wrong!