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) 140AnswerWhat’s the pattern?We want to match only phone numbers that contain exactly 10 digits (with optional spaces/hyphens)on a single line.In order to do this, we make our regex more rigid. We can do this by using the line anchors ˆ and $to indicate that we don’t expect any other kinds <strong>of</strong> characters besides the 10-digits and the optionalhypens/spaces.Find ˆ(\d{3})[ \-]?(\d{3})[ \-]?(\d{4})$Replace (\1)-\2-\3If you apply it to these sample numbers:255561640405556164040You will end up with:25556164040(555)-616-4040<strong>The</strong> first number is not transformed because it is not matched by the pattern.Exercise: Dial 1? If you’ve ever moved from <strong>of</strong>fice to <strong>of</strong>fice, one <strong>of</strong> the perplexing questions is:Do I have to dial 1 to make an outside call?So some people are used to having 1- be a part <strong>of</strong> their phone number, especially if they’re usingtheir <strong>of</strong>fice phone. Some <strong>of</strong> these people might add this prefix to their number out <strong>of</strong> reflex:1-555-241-5010555 981 270591124000001 101-555-7745AnswerIn English <strong>The</strong> same as before, except that the ten-digits might be preceded with the digit 1 andalso might be preceded by a hyphen or a whitespace character. <strong>The</strong>re’s no new techniquehere. We just need to use the ? operator at least once more.Find ˆ1?[ \-]?(\d{3})[ \-]?(\d{3})[ \-]?(\d{4})$

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

Saved successfully!

Ooh no, something went wrong!