1、Pattern 类:例子:Pattern pattern = Ppile(“,s+“);String result = pattern.split(“one two three,four,five, six“);for(int i = 0; iresult.length; i+)System.out.println(resulti);输出结果是:onetwothreefourfivesixPattern 类的静态方法 compile 用来编译正则表达式,在此,s+表示若干个“,“ 或者若干个空格匹配split 方法使用正则匹配将字符串切割成各子串并且返回Matcher 类:注意,Matcher
2、 的获得是通过 Pattern.matcher(CharSequence charSequence);输入必须是实现了 CharSequence 接口的类常用方法:matches()判断整个输入串是否匹配,整个匹配则返回 true例如下面会输出 trueString str1 = “hello“;Pattern pattern1 = Ppile(“hello“);Matcher matcher1 = pattern1.matcher(str1);System.out.println(matcher1.matches();lookingAt()从头开始寻找,找到匹配则返回 true例如下面会输出
3、 trueString str2 = “hello yangfan!“;Pattern pattern2 = Ppile(“hello“);Matcher matcher2 = pattern2.matcher(str2);System.out.println(matcher2.lookingAt();find()扫描输入串,寻找下一个匹配子串,存在则返回 true例如下面将会将所有 no 替换成 yesPattern pattern = Ppile(“no“);Matcher matcher = pattern.matcher(“Does jianyue love yangfan? no;“ +“Does jianyue love yangfan? no;Does jianyue love yangfan? no;“);StringBuffer sb = new StringBuffer();boolean find = matcher.find();while(find)matcher.appendReplacement(sb, “yes“);find = matcher.find();matcher.appendTail(sb);System.out.println(sb.toString();