In the previous examples, you were only matching expressions consisting of a few generic characters and literal words. To help write more expressive patterns, you use a quantifier metacharacter. The quantifiers are as follows:
? * + { }
The quantifiers allow you to determine the number of repeats of a portion of a regular expression you consider a match. Quantifiers are located immediately after the character, character class or grouping that you want to match. The following table defines each quantifier and its meaning.
The following are some examples using matching repetitions:
| Matching repetition | Description |
|---|---|
| ‘/\w+/’ | Any alphanumeric word (one or more alphanumeric characters together.) |
| ‘/-?\d+/’ | A number (one or more digits) optionally prefixed by a hyphen. |
| ‘/[a-z]+\t\d{1,5}/’ | Any lowercase word, followed by a tab, followed by 1 to 5 digits |
| ‘/\w+/’ | Any alphanumeric word (one or more alphanumeric characters together.) |
| ‘/The.*dog/’ | Any line that is followed by anything and then dog. Examples: The nice dog The quick brown fox jumped over the lazy dog The WhateverHeredog Thedog |
'/d{10}/' // 10 digits (no more, no less)
'/\d{3}-\d{3}-\d{4}/'
'/\d{3}-?\d{3}-?\d{4}/'
'/[1-9]\d{2}-?\d{3}-?\d{4}/'
Did you understand it? Let's study it in parts:
phone as String
input "Enter your phone number:" phone
if phone.isMatch('/[1-9]\d{2}-?\d{3}-?\d{4}/') then
display "OK, a valid phone number"
else
display "ERROR, invalid phone number"
end