一、正则表达式

1. Pattern与Matcher

(1) Pattern类

   Pattern类为模式类,它有一个static方法,compile(String str),能够生成一个以str为正则表达式的Pattern对象。
   Pattern p = Pattern.compile(str);   //str为正则表达式,用于匹配

(2) Matcher类

   Matcher类为匹配器类,通过Pattern对象的matcher(String str)方法生成Matcher对象
   Matcher m = p.matcher(str);   //str为需要被执行匹配的字符串

2. Matcher类的基本方法

(1) find()

   功能:m.find()方法对字符串进行匹配,匹配方式为以compile()方法中的参数为正则表达式来匹配matcher()方法中的参数的字符串。若匹配成功,返回true,否则返回false。
   例如:
   Matcher m = Pattern.compile("\w").matcher("I like bunches");
   正则表达式为"\w",表示词字符,被匹配的字符串为"I like bunches"。此时调用find(),将返回true,匹配的字符串为"I",同时向前遍历(类似迭代器)。再次调用m.find(),则返回true,匹配的字符串为"like",依次类推。

(2) group()

   功能:将匹配的String返回。
   通过find()匹配的字符串可以通过group()方法返回:
   while(m.find()){
     System.out.println(m.group());
   }

   输出:
   I
   like
   bunches