[dmtsai@study ~]$
grep
-
n 't[ae]st'
regular_express.txt
8:I can't finish the
test
.
9:Oh! The soup
tast
e good.
了½了吧?
其实
[]
里面不论有几个字符,他都½代表某『一个』字符
,
所以,上面的例子说明了,
我需要的字符串是『
tast
』或『
test
』两个字符串而已!
而如果想要搜寻到有
oo
的字符时,则使用:
[dmtsai@study ~]$
grep
-
n 'oo' regular_express.txt
1:"Open Source" is a g
oo
d mech
anism to develop programs.
2:apple is my favorite f
oo
d.
3:F
oo
tball game is not use feet only.
9:Oh! The soup taste g
oo
d.
18:g
oo
gle is the best t
oo
ls for search keyword.
19:g
oooooo
gle yes!
但是,如果我不想要
oo
前面有
g
的话呢?此时,可以利用在集合字符的反向选择
[^]
来达成:
[dmtsai@study ~]$
grep
-
n '[^g]oo' regular_express.txt
2:apple is my favorite
foo
d.
3:
Foo
tball game is not use feet only.
18:google is the best
too
ls for search keyword.
19:g
oooooo
gle yes!
意思就是说,我需要的是
oo
,但是
oo
前面不能是
g
就是了!仔细比½上面两个表格,妳会发现,
第
1,9
行不见了,因为
oo
前面出现了
g
所致!第
2,3
行没有疑问,因为
foo
与
Foo
均可被½受!
但是第
18
行明明有
google
的
goo
啊~别忘记了,因为该行后面出现了
tool
的
too
啊!所以该行
也被列出来~
也就是说,
18
行里面虽然出现了我们所不要的项目
(goo)
但是由于有需要的项目
(too)
,
因此,是符合字符串搜寻的喔!
至于第
19
行,同样的,因为
goooooogle
里面的
oo
前面可能是
o
,例如:
go(ooo)oogle
,所以,
这一行也是符合需求的!
再来,假设我
oo
前面不想要有小写字符,所以,我可以这样写
[^abcd....z]oo
,
但是这样似乎不怎
么方便,由于小写字符的
ASCII
上编码的顺序是连续的,
因此,我们可以½之简化为底下这样:
[dmtsai@study ~]$
grep
-
n '[^a
-
z]oo' regular_express.txt
3:
Foo
tball game is not use feet only.
也就是说,当我们在一组集合字符中,如果该字符组是连续的,例如大写英文
/
小写英文
/
数字等等,
就
可以使用
[a-z],[A-Z],[0-9]
等方式来书写,那么如果我们的要求字符串是数字与英文呢?
呵呵!就½
他全部写在一起,变成:
[a-zA-Z0-9]
。例如,我们要取得有数字的那一行,就这样:
[dmtsai@study ~]$
grep
-
n '[0
-
9]' regular_express.txt