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.

Changing phone format (TODO) 141Replace (\1)-\2-\3This pattern does the job <strong>of</strong> matching an optional 1 as well as an optional hyphen or whitespacebefore the actual ten digits <strong>of</strong> the phone number. We can use the same value for the Replace fieldbecause we’re using the same captured groups.If you apply it to the following numbers:55561640401 555 29290102 555 616 4040<strong>The</strong> resulting transformation is:(555)-616-4040(555)-292-90102 555 616 4040<strong>The</strong> last number is not transformed because its prefix is a 2, which is something we don’t expect (ina standard U.S. number).A more precise grouping<strong>The</strong>re’s something a bit <strong>of</strong>f to the previous solution. Since both the 1 and the whitespace/hyphenare optional, that means our regex would also match the following:-555-212-0000And turn it into:(555)-212-0000You might think: Yeah, so? Well, it’s true that there’s probably no harm done in matching (and thenignoring) a stray hyphen, sometimes you have to ask, why is there a stray hyphen without a 1? Itmay be harmless to us, but it might indicate that the user misunderstood what was supposed to bethe phone field. Perhaps they’re trying to enter an international format and got cut<strong>of</strong>f.Who knows. But just to be safe, let’s make our regex more rigid so that it won’t match that kind <strong>of</strong>input. In other words, we want a regex that matches:

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

Saved successfully!

Ooh no, something went wrong!