正则表达式上下文中的字符类是一组用方括号括起来的字符"[]"。它指定将成功匹配给定输入中的单个字符的字符。
简单类是字符类的最基本形式,只需将一组字符并排放在方括号内即可形成。例如,正则表达式b[ai]t将匹配单词,"bit"或者"bat"因为该模式定义了一个接受"i"或"a"作为中间字符的字符类。
package org.nhooo.example.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CharacterClassesSimpleClassDemo { public static void main(String[] args) { // 创建字符类的简单类类型。 // 以下正则表达式将搜索所有序列 // 以“ b”开头,以“ t”结尾并具有 // 中间字母“ a”或“ i”。 String regex = "b[ai]t"; // 编译模式并获得匹配对象。 Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher("I'm a little bit afraid of bats " + "but not cats."); // 找到所有匹配项并打印出来。 while (matcher.find()) { System.out.format("Text \"%s\" found at %d to %d.%n", matcher.group(), matcher.start(), matcher.end()); } } }
该程序将打印以下输出:
Text "bit" found at 13 to 16. Text "bat" found at 27 to 30.