Linux Bash之正則表達式

首先注意:正則表達式與通配符是徹底不一樣的概念。通配符 (wildcard) 表明的是 Bash 操做接口的一個功能,而正則表達式是一種字符串處理的表示方式,必定要區分開來。html

正則表達式 (Regular Expression) 是經過一些特殊字符的排列,用以查找/替換/刪除一行或多行文字字符串。也便是說,正則表達式是用在字符串處理上的一項表達式,它不是一個工具程序,而是一個字符串處理的標準依據,若是咱們想以正則表達式的方式處理字符串,就要使用支持正則表達式的工具程序,如 vim、sedawkgrep 等。linux

A regular expression is a pattern that describes a set of strings.
regexp are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions.
grep understands three different regexp syntax: 「basic」 (BRE), 「extended」 (ERE) and 「perl」 (PCRE).
In GNU grep, there is no difference in available functionality between basic and extended syntaxes.

 首先介紹第一部分,基本正則表達式的基本組成部分,見表1-1,若是想要在大部分機器上均可以使用的可移植腳本,只使用基本組成部分是一個好的選擇。正則表達式

 而後來看第二部分,對於Shell中的POSIX字符,如表1-2所示,基本上能夠根據符號猜出其含義,即所謂望文生義,比較容易記憶。這部分對基本正則,擴展正則以及Perl格式的正則表達都是同樣的,特定的符號特定的含義。shell

Such certain named classes of characters are predefined within bracket expressions. Their names are self explanatory.

 

 接下來是第三部分,元字符及其含義和使用示例,如表1-3所示,這裏也只是給出基本正則和擴展正則中支持的元字符,對於Perl風格的正則能支持的更多的字符在稍後的部分展現。 express

The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word.
The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]].
The symbols \< and \> respectively match the empty string at the beginning and end of a word.

第四部分,對於擴展正則以及Perl風格的正則,其所支持的功能更多更復雜,使用起來也是更方便,其在基本正則的基礎上又有一些新的表示和約定,如表1-4所示。vim

 最後一部分,Perl風格的正則相對於基本正則和擴展正則而言能支持更豐富的元字符,如表1-5所示,有了更多的定義和用法。ide

參考資料工具

[1] Shell正則表達式spa

[2] ASCII.net

相關文章
相關標籤/搜索