基礎Regex
1. RegexRegex是處理字串的方法,以行為單位進行處理。2. 基礎Regex字元使用下面的特殊字元
^string 以string開頭的 grep '^w' test test檔案中以w開頭的行string$ 以string結尾的 grep 'day$' test 以day結尾的行. 匹配任一字元 grep -n 'go.d' test 找到 good goad 等\ 逸出字元, 將特殊字元進行轉義 grep t\'his test* 重複0次或多次 grep 'go*d' test 找到 good[list] 找出選取的字元[n1-n2] 找出選取的字元範圍 grep '[0-9]' filename 找到包含數位 [a-z] 包含所有小寫字母[^list] 不包括選取的字元\{n,m\} 匹配n到m次前一個字元 \{n\}出現n詞, \{n,\}出現n次以上3. 語系對Regex的影響不同語系的編碼資料並不相同。例如英文大小寫編碼: LANG=C時, 0 1 2 3 ... A B C ... Z a b c ... z LANG=zh_CN時, 0 1 2 3 .... a A b B c C ... z Z 所有當我們取 [A-Z] 時, LANG=C 把大寫A-Z取出來而LANG=zh_CN.gb2312 會把b-z也取出來。為了避免這個問題, 使用Regex時,使用的是相容於 POSIX 的標準。
[:digit:]Only the digits 0 to 9 匹配數字[:alnum:]Any alphanumeric character 0 to 9 OR A to Z or a to z. 字母和數字[:alpha:]Any alpha character A to Z or a to z. 字母A-Z, a-z[:blank:]Space and TAB characters only. 匹配空格和 tag[:xdigit:]Hexadecimal notation 0-9, A-F, a-f. 16進位數字[:punct:]Punctuation symbols . , " ' ? ! ; : # $ % & ( ) * + - / < > = @ [ ] \ ^ _ { } | ~ 標點符號[:print:]Any printable character. 可列印字元[:space:]Any whitespace characters (space, tab, NL, FF, VT, CR). Many system abbreviate as \s. 任何產生空白的字元[:graph:]Exclude whitespace (SPACE, TAB). Many system abbreviate as \W. 除了空格和tag外的其他按鍵[:upper:]Any alpha character A to Z. 大寫[:lower:]Any alpha character a to z. 小寫[:cntrl:]Control Characters NL CR LF TAB VT FF NUL SOH STX EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL. 代表鍵盤上的修飾鍵通常與[] 一起使用,例如:
grep '[[:digit:]]' test 找到數字 grep '[[:alpha:]]' test 找到字母
地址:http://blog.csdn.net/yonggang7/article/details/39118991