java 通过正则表达式获取匹配字符串的例子

public class TestJava {

    public static void main(String[] args) {

        String text="wefawefaafickdbbjoasdfcweccwerqeasdaajfnblsdbboioe";
        String replaceText="&";//匹配到 替换的文字
        StringBuffer sb=new StringBuffer();
        Pattern pattern=Pattern.compile("(aa|bb|cc)");//正则表达式 匹配 aa或bb或bb
        Matcher matcher= pattern.matcher(text);
        while(matcher.find()){
            matcher.appendReplacement(sb, replaceText);
            String s=matcher.group();//得到匹配的结果
            System.out.println(s);
        }
        matcher.appendTail(sb);

        System.out.printf(sb.toString());

    }
    
}

输出结果:

aa
bb
cc
aa
bb
wefawef&fickd&joasdfcwe&werqeasd&jfnblsd&oioe

你可能感兴趣的:(java)