在regex中,您还具有许多预定义的字符类,它们为常用字符集提供了一种简写形式。
列表如下:
预定义类 | 匹配 |
---|---|
. | 任何字符 |
d | 任何数字,简写 [0-9] |
D | 一个非数字, [^0-9] |
s | 空格字符 [^s] |
S | 任何非空白字符 |
w | 文字字符 [a-zA-Z_0-9] |
W | 非文字字符 |
package org.nhooo.example.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PredefinedCharacterClassDemo { public static void main(String[] args) { // 定义正则表达式,它将搜索后跟f的空格 // 和两个任意字符。 String regex = "\\sf.."; // 编译模式并获得匹配对象。 Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher( "The quick brown fox jumps over the lazy dog"); // 找到每一个匹配并打印 while (matcher.find()) { System.out.format("Text \"%s\" found at %d to %d.%n", matcher.group(), matcher.start(), matcher.end()); } } }
该程序输出以下结果:
Text " fox" found at 15 to 19.