Java如何使用预定义字符类regex?
在regex中,您还具有许多预定义的字符类,它们为常用字符集提供了一种简写形式。
列表如下:
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.