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.

Optionality and alternation 95Answer<strong>The</strong> solution pattern is ugly and convoluted looking. But if you take it one character at a time, fromleft to right, and simply put a question mark after each optional character, it’s not at all tricky.Remember to backslash-escape the special characters.Find 1?-?\(?\d{3}\)?-?\d{3}-?\d{4}Precedence with parentheses and optionalityAs with most regex operators, the ? only affects what directly precedes it, whether it’s a singlecharacter or a complex pattern.If what you make optional is more than just a single character, then use parentheses so that theentire group <strong>of</strong> characters is modified by the ?Given a list <strong>of</strong> dollar amounts:$200 $19.20 $610.42 $1.5 $15<strong>The</strong> following pattern –\$\d+\.\d{2}?– will match only two <strong>of</strong> the listed amounts:$200 $19.20 $610.42 $1.5 $15However, by using parentheses to make optional the literal decimal point and the two numericaldigits, we can match all the listed amounts:\$\d+(\.\d{2})?And again, if you aren’t intending to use parentheses to capture any part <strong>of</strong> the text, then you shoulduse the non-capturing version:\$\d+(?:\.\d{2})?Which might lead you to ask: how do you tell those question marks apart?For example, consider the pattern:

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

Saved successfully!

Ooh no, something went wrong!