13.5 预定义字符类
Pattern API包含很多有用的预定义字符类(predefined character class),它们提供常用正则表达式便利的简写方式。
在表13-2中,左边一列的每个结构是右边一列的字符类的简写方式。例如,\d表示数字范围(0-9),而\w表示单词字符(任何小写字母、任何大写字母、下划线或者任何数字)。应该尽可能使用预定义类。它们使你的代码更容易阅读,并且排除易混淆的字符类造成的错误。
表13-2 预定义字符类
|
. |
任何字符(可能匹配,也可能不匹配行终止符) |
|
\d |
数字:[0-9] |
|
\D |
非数字:[^0-9] |
|
\s |
空白字符:[ \t\n\x0B\f\r] |
|
\S |
非空白字符:[^\s] |
|
\w |
单词字符:[a-zA-Z_0-9] |
|
\W |
非单词字符:[^\w] |
以反斜线开头的结构被称为转义结构(escaped construct)。我们在3.1.2节的第2小节简单介绍了转义结构,其中提到了用于引用的反斜线、\Q和\E。如果你在字符串字面量中使用转义结构,就必须在反斜线前面再加上一个反斜线,以便能够编译字符串。例如:
private final String REGEX = "\\d"; // a single digit
在这个例子中,\d是正则表达式;附加的反斜线是编译代码所必须的。但是,测试示例直接从控制台读取表达式,所以附加的反斜线不是必须的。
下面的例子演示预定义字符类的使用:
Enter your regex: .
Enter input string to search: @
I found the text "@" starting at index 0 and ending at index 1.
Enter your regex: .
Enter input string to search: 1
I found the text "1" starting at index 0 and ending at index 1.
Enter your regex: .
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \d
Enter input string to search: 1
I found the text "1" starting at index 0 and ending at index 1.
Enter your regex: \d
Enter input string to search: a
No match found.
Enter your regex: \D
Enter input string to search: 1
No match found.
Enter your regex: \D
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \s
Enter input string to search:
I found the text " " starting at index 0 and ending at index 1.
Enter your regex: \s
Enter input string to search: a
No match found.
Enter your regex: \S
Enter input string to search:
No match found.
Enter your regex: \S
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \w
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \w
Enter input string to search: !
No match found.
Enter your regex: \W
Enter input string to search: a
No match found.
Enter your regex: \W
Enter input string to search: !
I found the text "!" starting at index 0 and ending at index 1.
在前三个例子中,正则表达式是简单的.(“点号”元字符表示“一个任何字符”)。因此,前三个例子都匹配成功(其中随机地使用一个@字符、一个数字和一个字母)。其余的例子分别使用表13-2中的正则表达式结构。可以参考这个表来分析每个匹配背后的逻辑:
l \d匹配所有数字。
l \s匹配空白。
l \w匹配单词字符。
另一种方式是使用大写字母表示相反含义:
l \D匹配非数字。
l \S匹配非空白。
l \W匹配非单词字符。






