1.4.4 Alternation
1.4.4.1 Matching any one of several subexpressions
A very convenient metacharacter is 「|」,which means “or”.
能够匹配总的表达式中的任意一个的子表达式,在这样的组合中,子表达式称为”多选分支(alternative)”。
例如,
% egrep '^(From|Subject|Date): ' mailbox
From: elvis@tabloid.org (The King)
Subject: be seein' ya around
Date: Mon, 23 Oct 2006 11:04:13
From: The Prez <president@whitehouse.gov>
Date: Wed, 25 Oct 2006 8:36:24
Subject: now, about your vote...
.
.
.
1.4.5 Ignoring Differences in Capitalization
The email header example provide a goodopportunity to introduce the concept of a case-insensitivematch.
在egrep参数中加”-i” 即可实现不区分大小写(case-insensitive)。
% egrep -i '^(From|Subject|Date): ' mailbox
1.4.6 Word Boundaries
单词分界符指的是:把某些特殊符号放到单词开头和结束的位置。
元字符序列(metasequences):「\<」、「\>」
相当于「^」和「$」
1.4.7 In a Nutshell
Table1-1. Summary of Metacharacters Seen So Far.
Metacharacter | Name | Matches |
. | dot | any one character |
[…] | character class | any character listed |
[^…] | negated character class | any character not listed |
^ | caret | the position at the start of the line |
$ | dollar | the position at the end of the line |
\< | backslash less-than | †the position at the start of a word |
\> |
| †not supported by all versions of egrep |
| | or; bar | Matches either expression it separates |
(…) | parentheses | Used to limit scope of 「|」, plus additional uses yet to be discussed |
需要注意几点:
l在字符组内部,元字符的定义规则(及它们的意义)是不一样的。例如,在字符组外部,点号(.)是元字符,但是在内部则不是如此。相反,连字符(-)只有在字符组内部(这是普通情况)才是元字符,否则就不是。脱字符(^)在字符组外部表示一个意思,在字符组内部紧接着[时表示另一个意思,其他情况下又表示别的意思。
l不要混淆多选项(Alternation)和字符组(Character classes)。字符组「[abc]」和多选项「(a|b|c)」固然表示同一个意思,但是这个例子中的相似性并不能推广开来。无论列出的字符有多少,字符组只能匹配一个字符。相反,多选项可以匹配任意长度的文本,每个多选项可能匹配的文本都是独立的,例如「\<(1000000|million|thousand·thou)\>」。不过,多选项没有字符组那样的排除功能。
l排除型字符组是表示所有未列出字符的字符组的简便方法。因此,「[^x]」的意思并不是“只有当这个位置不是x时才能匹配“,而是说”匹配一个不等于x的字符“。其中的差别很细微,但很重要。例如,前面的概念可以匹配一个空行,而「[^x]」则不行。
1.4.8 Optional Items
元字符「?」代表可选项(Optional Items)。
把它加在一个字符的后面,就表示此处容许(也可以不)出现这个字符。
1.4.9 Other Quantifiers: Repetition
问号、加号和星号,统称为量词(quantifiers)
问号(?)表示前一项出现1次或者0次。
加号(+)表示可以匹配前一项的1次或者多次。
星号(*)表示匹配前一项0次或者多次。