< Previous | Contents | Next >
{ } - Match An Element A Specific Number Of Times
The { and } metacharacters are used to express minimum and maximum numbers of re- quired matches. They may be specified in four possible ways:
Table 19-3: Specifying The Number Of Matches
Specifier Meaning
Specifier Meaning
{n} Match the preceding element if it occurs exactly n times.
{n,m} Match the preceding element if it occurs at least n times, but no more than m times.
{n,} Match the preceding element if it occurs n or more times.
{,m} Match the preceding element if it occurs no more than m times.
Going back to our earlier example with the phone numbers, we can use this method of specifying repetitions to simplify our original regular expression from:
^\(?[0-9][0-9][0-9]\)? [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$
to:
^\(?[0-9]{3}\)? [0-9]{3}-[0-9]{4}$
Let’s try it:
[me@linuxbox ~]$ echo "(555) 123-4567" | grep -E '^\(?[0-9]{3}\)? [0- 9]{3}-[0-9]{4}$'
(555) 123-4567
[me@linuxbox ~]$ echo "555 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9]
{3}-[0-9]{4}$'
555 123-4567
[me@linuxbox ~]$ echo "5555 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9
]{3}-[0-9]{4}$'
[me@linuxbox ~]$
[me@linuxbox ~]$ echo "(555) 123-4567" | grep -E '^\(?[0-9]{3}\)? [0- 9]{3}-[0-9]{4}$'
(555) 123-4567
[me@linuxbox ~]$ echo "555 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9]
{3}-[0-9]{4}$'
555 123-4567
[me@linuxbox ~]$ echo "5555 123-4567" | grep -E '^\(?[0-9]{3}\)? [0-9
]{3}-[0-9]{4}$'
[me@linuxbox ~]$
As we can see, our revised expression can successfully validate numbers both with and without the parentheses, while rejecting those numbers that are not properly formatted.