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) 138Exercise: Grouped digits, possibly separated by spaces Instead <strong>of</strong> requiring users to give us 10straight digits, we allow them to use spaces. Why might we do this? Because it reduces mistakeson the user end. Sure, they might know their phone number as well as their birthdate. But usingspaces lets them more easily spot typos. Compare reading 5553121121 to 555 312 1121So now our regex has to expect this kind <strong>of</strong> input (as well as 10 straight digits):5552415010555 981 27059112400000101 555 7745Answer We want to match 10 numerical digits in three capturing groups. However, there may ormay not be a space between each group.This is a perfect time to use the ? operator.Find (\d{3}) ?(\d{3}) ?(\d{4})Replace (\1)-\2-\3<strong>The</strong> question mark signifies that the preceding whitespace character is optional. Note that theReplace value doesn’t have to change, because the capturing group still contains the same number<strong>of</strong> digits.Exercise: Grouped digits, possibly separated by a hyphen or a space Many people use hyphensinstead <strong>of</strong> space-characters to separate their phone digits. We need to change our regex to matchthat possibility.555-241-5010555 981 27059112400000101-555 7745What’s the pattern?We want to match 10 numerical digits in three capturing groups. However, there may or may notbe a space – or a hyphen – between each group.We can use the ? operator as before, but we’ll throw in a character set to handle either a hyphen ora whitespace character.

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

Saved successfully!

Ooh no, something went wrong!