名詞解釋
正則表達(dá)式(regular expression, RE)是一種字符模式和敬,用于在查找過(guò)程中匹配指定的字符。
在大多數(shù)程序里讨永,正則表達(dá)式都被置于兩個(gè)正斜杠之間瞪浸;例如/l[oO]ve/就是由正斜杠界定的正則表達(dá)式生真,它將匹配被查找的行中任何位置出現(xiàn)的相同模式。在正則表達(dá)式中捺宗,元字符是最重要的概念柱蟀。
定義:元字符是這樣一類(lèi)字符,它們表達(dá)的是不同于字面本身的含義
基本正則表達(dá)式元字符
表達(dá)式 | 含義 |
---|---|
^ | 行首定位符 |
$ | 行尾定位符 |
. | 匹配單個(gè)字符 |
* | 匹配前導(dǎo)符0到多次 |
.* | 匹配任意多個(gè)字符 |
[ ] | 匹配指定范圍內(nèi)的一個(gè)字符 |
[ - ] | 匹配指定范圍內(nèi)的一個(gè)字符蚜厉,連續(xù)的范圍 |
[^] | 匹配不在指定范圍內(nèi)的字符 |
\ | 用來(lái)轉(zhuǎn)義元字符长已,褪去特殊含義 |
\< | 詞首定位符 |
\> | 詞尾定位符 |
( ) | \(..\) 匹配稍后使用的字符的標(biāo)簽 |
x\{m\} | 字符x重復(fù)出現(xiàn)m次 |
x\{m,\} | 字符x重復(fù)出現(xiàn)m次以上 |
x\{m,n\} | 字符x重復(fù)出現(xiàn)m次到n次 |
拓展正則表達(dá)元式字符
表達(dá)式 | 含義 |
---|---|
+ | 匹配1~n個(gè)前導(dǎo)字符 |
? | 匹配0~1個(gè)前導(dǎo)字符 |
a|b | 匹配a或b |
( ) | 組字符 |
示例 1:
// 查找匹配
#找到love開(kāi)頭的行
[root@localhost ~]# egrep "^love" file
#找到love結(jié)尾的行
[root@localhost ~]# egrep "love$" file
#找到l開(kāi)頭,一個(gè)任意字符昼牛,ve結(jié)尾
[root@localhost ~]# egrep "l.ve" file
#l開(kāi)始痰哨,零個(gè)或多個(gè)o,ve結(jié)尾
[root@localhost ~]# egrep "lo*ve" file
#大L 或者小L 開(kāi)頭的 ove
[root@localhost ~]# egrep "[Ll]ove" file
#love最后一個(gè)小寫(xiě)字母
[root@localhost ~]# egrep "love[a-z]" file
#love最后一個(gè)(不是字母或者數(shù)字)匾嘱,而是符號(hào)
[root@localhost ~]# egrep "love[^a-zA-Z0-9]" file
示例 2:
// 查找匹配
#找到所有行
[root@localhost ~]# egrep ".*" file
#找到空行
[root@localhost ~]# egrep "^$" file
#開(kāi)頭一個(gè)大寫(xiě),最后2個(gè)任意字符
[root@localhost ~]# egrep "^[A-Z]..$" file
#一個(gè)大寫(xiě)開(kāi)頭早抠,0到多個(gè)小寫(xiě)或空格霎烙,3,最后是0-5的一個(gè)數(shù)字
[root@localhost ~]# egrep "^[A-Z][a-z ]*3[0-5]" file
#0到多個(gè)小寫(xiě)字母蕊连,最后一個(gè)點(diǎn)
[root@localhost ~]# egrep "[a-z]*\." file
#0到多個(gè)空格開(kāi)頭悬垃,一個(gè)大寫(xiě),一個(gè)小寫(xiě)甘苍,再一個(gè)小寫(xiě)結(jié)尾
[root@localhost ~]# egrep "^ [A-Z][a-z]*[a-z$]" file
#0到多個(gè)字母開(kāi)頭尝蠕,非逗號(hào),0到多個(gè)英文結(jié)尾
[root@localhost ~]# egrep "[A-Za-z]*[^,][A-Za-z]*" file
#找到 fourth 單詞
[root@localhost ~]# egrep "\<fourth\>" file
#找到f開(kāi)頭th結(jié)尾的單詞
[root@localhost ~]# egrep "\<f.*th\>" file
#找到5兩次2三次和一個(gè)點(diǎn)
[root@localhost ~]# egrep "5{2}2{3}\." file
#找到0到多個(gè) 载庭,空格或tab的行
[root@localhost ~]# egrep "[ \t]*" file
#找到以#號(hào)開(kāi)頭的行
[root@localhost ~]# egrep "^#" file
#找到有0到多個(gè),空格或者tab開(kāi)頭的行,的注釋行
[root@localhost ~]# egrep "^[ \t]*#" file
#過(guò)濾掉空行與\#注釋的行
[root@localhost ~]# egrep -v "^$|#" file