基础正则表达式

来源:互联网 发布:淘宝上付费引流的软件 编辑:程序博客网 时间:2024/06/06 21:19

1. 正则表达式


正则表达式是处理字符串的方法,以行为单位进行处理。

2. 基础正则表达式字符


使用下面的特殊字符
^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. 语系对正则表达式的影响


不同语系的编码数据并不相同。
例如英文大小写编码:
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也取出来。
为了避免这个问题, 使用正则表达式时,使用的是兼容于 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


0 0