package com.mutouyihao; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 正则表达式的应用开发的类主要有pattern、matcher * pattern存储经过编译的正则表达式,matcher对象是一个状态机,根据pattern对字符串进行检查 * 流程: * 首先创建pattern对象,然后由pattern生成matcher * mather的方法: * 查找: * mathes():整个字符串匹配则返回真值 * lookingAt():检测是否以匹配的子串开始 * find():在目标字符串中查找下一个匹配子串 * * 替换: * replaceAll(String rpl):替换所有匹配成功的子串 * replaceFirst(String rpl):替换第一个匹配的子串 * appendReplacement(StrinBuffer sb, String replacement) * 将当前匹配的子串替换,且将替换后的子串及之前到上次匹配的串放到sb * appendTail(StringBuffer sb) * 将最后一次匹配工作后剩余的字符串添加到sb中 */ public class testGoto { public static void main(String[] args){ String input = "This is test and that is test too. Try your test. Make it tested."; Pattern p = Pattern.compile("//btest");///b表示单词间,"/btest/b"则只匹配test单词 Matcher m = p.matcher(input); StringBuffer sb = new StringBuffer(); System.out.println("mathes():"+m.matches()); System.out.println("find():"+m.find()); System.out.println("lookingAt():"+m.lookingAt()); int counts = 0; while(m.find()) { m.appendReplacement(sb, "regex"); counts++; System.out.println("第"+counts+"次匹配后sb内容:"+sb); } m.appendTail(sb); System.out.println("last string is :"+ sb); } }