The Linux Command Line by Shotts William E

The Linux Command Line by Shotts William E

Author:Shotts, William E. [William E. Shotts Jr.]
Language: eng
Format: epub
Tags: COMPUTERS / Operating Systems / Linux
ISBN: 9781593274269
Publisher: No Starch Press
Published: 2012-01-14T16:00:00+00:00


Quantifiers

Extended regular expressions support several ways to specify the number of times an element is matched.

?—Match an Element Zero Times or One Time

This quantifier means, in effect, “Make the preceding element optional.” Let’s say we wanted to check a phone number for validity and we considered a phone number to be valid if it matched either of these two forms, (nnn) nnn-nnnn or nnn nnn-nnnn, where n is a numeral. We could construct a regular expression like this:

^\(?[0-9][0-9][0-9]\)? [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$

In this expression, we follow the parentheses characters with question marks to indicate that they are to be matched zero or one time. Again, since the parentheses are normally metacharacters (in ERE), we precede them with backslashes to cause them to be treated as literals instead.

Let’s try it:

[me@linuxbox ˜]$ echo "(555) 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9] [0-9][0-9]$' (555) 123-4567 [me@linuxbox ˜]$ echo "555 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9] [0-9][0-9]-[0-9][0-9][0-9][0-9]$' 555 123-4567 [me@linuxbox ˜]$ echo "AAA 123-4567" | grep -E '^\(?[0-9][0-9][0-9]\)? [0-9] [0-9][0-9]-[0-9][0-9][0-9][0-9]$' [me@linuxbox ˜]$

Here we see that the expression matches both forms of the phone number but does not match one containing non-numeric characters.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.