1. 程式人生 > >bash Shell 總結《四》 正則表達式

bash Shell 總結《四》 正則表達式

ja

正則表達式


單個字符表示法


字符本身 <-- 除了下面的特殊字符之外,字符可以表示其本身

. <-- Any character

\d <-- Digit in 0123456789

\D <-- Non-digit

\w <-- Word: letters, digits, underscore (_)

\W <-- Non-word

\t <-- Tab

\r <-- Carriage return

\n <-- New line

\s <-- Whitespace: space, \t, \r, \n

\S <-- Non-whitespace

[abc] <-- a, or b, or c

[a-c] <-- a, or b, or c

[0-2] <-- 0, or 1, or 2

[1-3a-cX-Z] <-- 1, 2, 3, a, b, c, X, Y, Z

[^abc] <-- Any character except a and b and c

[:upper:] <-- Upper case letters, [A-Z]

[:lower:] <-- Lower case letters, [a-z]

[:alpha:] <-- Alphabetic characters, [a-zA-Z]

[:alnum:] <-- Alphanumeric characters, [a-zA-Z0-9]

[:digit:] <-- Digits, [0-9]

[:xdigit:] <-- Hexadecimal digits, [a-fA-F0-9]

[:punct:] <-- Punctuation and symbols, [][!"#$%&'()*+,./:;<=>?@\^_`{|}~-]

[:blank:] <-- Space and tab, [ \t]

[:space:] <-- All whitespace characters including line breaks, [ \t\r\n\v\f]

[:cntrl:] <-- Control characters, [\x00-\x1F\x7F]

[:graph:] <-- Visible characters (i.e. anything except spaces, control characters, etc.), [\x21-\x7E]

[:print:] <-- Visible characters and spaces (i.e. anything except control characters, etc.), [\x20-\x7E]

[:word:] <-- Word characters (letters, numbers and underscores), [a-zA-Z0-9_]

[:ascii:] <-- ASCII characters, [\x00-\x7F]




特殊字符表示法


^$.*+?|\{}[]() 都有特殊意義的,如果需要表示這些符號,則可以用反斜杠對它們進行轉義,比如:

\. 匹配一個點

\\ 匹配一個反斜杠

\^

\$


出現在[...]中的連字符也有特殊意義,如果需要在[...]中表示一個連字符,就要把它放到[...] 的頭部或者尾部,比如:

[abc-] 或者 [-abc]




數量表示法


用來表示前面的一個字符,或者一組字符重復的次數

* <-- 任意次, {0,}, c >= 0

+ <-- 至少1次, {1,}, c >= 1

? <-- 0次或者1次, {0,1}, c == 0 || c == 1

{m} <-- m 次, c == m

{m,} <-- 至少m 次, c >= m

{m,n} <-- m 次至n 次, c >= m && c <= n


數量表示符作用於前面的一個字符,或者一組字符,用小括號括起來的就是一組字符。

ab+ 匹配ab, abb, abbb, abbbb...

(ab)+ 匹配ab, abab, ababab, abababab...


默認情況下,數量表示符是最大匹配,某些正則表達式引擎支持用問號 ? 來啟用最小匹配

.*b 匹配 aaabababa <-- 最大匹配

^^^^^^^^

.*?b 匹配 aaabababa <-- 最小匹配

^^^^




分組表示法


(abc) <-- 一組連續的字符abc

(aa|bb) <-- 一組連續的字符ab 或者 bb




邊界表示法


^ <-- 字符串的開頭

$ <-- 字符串的結尾

\b <-- 單詞邊界

\B <-- 非單詞邊界

\< <-- 單詞左邊界

\> <-- 單詞右邊界




引用表示法


從左邊開始數左小括號(openning brace),數字從1開始,被第一對括號匹配的字符可以用\1 來引用,第二對可以用\2 來引用,以此類推。

[czl@mob shell_03]$ echo abcabcabcaabb | grep -E '(a(bc)){2}\1' --color

abcabcabcaabb

[czl@mob shell_03]$ echo abcabcabcaabb | grep -E '(a(bc)){2}a\2' --color

abcabcabcaabb

[czl@mob ~]$ echo "hello world, hello world, hello beautiful world" | grep -E --color '((hello) (world)), \1, \2 .* \3'

hello world, hello world, hello beautiful world


bash Shell 總結《四》 正則表達式