正则表达式

正则表达式特殊符号

首先是正则表达式的特殊符号:

1
2
3
4
5
6
7
8
9
10
11
12
[:alnum:]代表英文大小写字母及数字
[:alpha:]代表英文大小写字母
[:blank:]代表空格和 tab 键
[:cntrl:]键盘上的控制按键,如 CR,LF,TAB,DEL
[:digit:]代表数字
[:graph:]代表空白字符以外的其他
[:lower:]小写字母
[:print:]可以被打印出来的任何字符
[:punct:]代表标点符号
[:upper:]代表大写字母
[:space:]任何会产生空白的字符如空格,tab,CR 等
[:xdigit:]代表 16 进位的数字类型

特殊符号实例

在 WebIDE 中使用 touch 命令或图形界面新建一个 .txt 文件并将下文中的文本内容复制进去。

1
touch regular_express.txt

也可以使用 wget 指令从本节开头的实验环境说明处下载,这两种方式取得的文件是一样的。

文本内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
"Open Source" is a good mechanism to develop programs.
apple is my favorite food.
Football game is not use feet only.
this dress doesn't fit me.
However, this dress is about \$ 3183 dollars.
GNU is free air not free beer.
Her hair is very beauty.
I can't finish the test.
Oh! The soup taste good.
motorcycle is cheap than car.
This window is clear.
the symbol '\*' is represented as start.
Oh!My god!
The gd software is a library for drafting programs.
You are the best is mean you are the no. 1.
The world <Happy> is the same with "glad".
I like dog.
google is the best tools for search keyword.
goooooogle yes!
go! go! Let's go.

# I am VBird

1-2-0

使用特殊符号查找小写字母:

1
grep -n '[[:lower:]]' regular_express.txt

红色为匹配成功的字符

1-2-1

使用特殊符号查找数字:

1
grep -n '[[:digit:]]' regular_express.txt

1-2-2

语系对正则表达式的影响

我们知道,计算机可以直接处理的文件中只有 0 和 1,我们看到的字符文字和数字都是通过编码表转换而来的。不同语系的编码不同会导致不同语系的数据选取结果有所差异。 以英文大小写为例,zh_CN.big5 及 C 这两种语系差异如下:

  • LANG=C 时: 0 1 2 3 4….A B C D E…Z a b c d e…z
  • LANG=zh_CN.big5 时:0 1 2 3 4…a A b B c C d D…..z Z

在使用正则表达式[A-Z]时, LANG=C 的情况下,找到的是大写字符 A B C D…Z。而在 LANG=zh_CN.big5 的情况下,会选取到 A b B c C d D…z Z。所以在使用正则表达式时要特别留意语系。

由于我们一般使用的是兼容于 POSIX 的标准,因此建议使用 C 语系。

需要说明的是,我们实验环境使用的 WebIDE 的默认语系 zh_CN.UTF-8 并没有该编码问题,可以直接使用。

可以使用 echo $LANG 指令查看当前语系。