Linux Bash之正则表达式

首先注意:正则表达式与通配符是完全不同的概念。通配符 (wildcard) 代表的是 Bash 操作接口的一个功能,而正则表达式是一种字符串处理的表示方式,一定要区分开来。

正则表达式 (Regular Expression) 是通过一些特殊字符的排列,用以查找/替换/删除一行或多行文字字符串。也即是说,正则表达式是用在字符串处理上的一项表达式,它不是一个工具程序,而是一个字符串处理的标准依据,如果我们想以正则表达式的方式处理字符串,就要使用支持正则表达式的工具程序,如 vim、sedawkgrep 等。

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格式的正则表达都是一样的,特定的符号特定的含义。

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

 

 接下来是第三部分,元字符及其含义和使用示例,如表1-3所示,这里也只是给出基本正则和扩展正则中支持的元字符,对于Perl风格的正则能支持的更多的字符在稍后的部分展示。 

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所示。

 最后一部分,Perl风格的正则相对于基本正则和扩展正则而言能支持更丰富的元字符,如表1-5所示,有了更多的定义和用法。

参考资料

[1] Shell正则表达式

[2] ASCII

猜你喜欢

转载自www.cnblogs.com/phillee/p/10949796.html