w7r.blogspot.com
Tutorial #2 Answers
- "a{3}b{4}c{5}"
- "kne{2}"
- "cab{2}age"
- "2{2}nd stre{2}t"
Typical Regex
Often times, the data we are trying to capture using Regex is not exactly clear. For example, with Regex you may want to capture all of the phone numbers on a website without knowing what actual numbers you will find.
Searching the literal text "333-333-3333" would not be a means of locating all of the phone numbers on a website. It would only capture results with that exact phone number.
So, we need to describe a pattern that follows: 3 digits + hyphen + 3 digits + hyphen + 4 digits.
The Digit Character
"\d" is the text to describe 1 digit. A digit character can only match: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
So, "\d\d\d" could match the first three digits of a phone number; however, we can simplify this expression to be "\d{3}". The curly brackets surround the exact number of digits we want to target.
So far "\d{3}" matches the 1st of 5 parts in the phone number pattern we would like to describe. The part following the three digits is a hyphen "-". A hyphen is treated literally in regex because the hyphen has no other purpose in regex besides specifying ranges which appear only in the quantity specifying portion of a regular expression.