正規表現の文字列操作時のいくつかの応用

1444 ワード

package com.yonge.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        //          
        Pattern p = null;
        Matcher matcher = null;
        p = Pattern.compile("[\\s]");
        String[] str = p.split("abcbbc cbc safdf");
        if (null != str) {
            for (String s : str)
                System.out.println("   :" + s);
        }
        p = Pattern.compile("[\\w]+");
        matcher = p.matcher("a1c b2c c3c");
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
        System.out.println(matcher.matches());

        //          
        p = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
        matcher = p.matcher("JAVA java JAva");
        //System.out.println(matcher.replaceAll("abc"));
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (matcher.find()) {
            if (i % 2 == 0) {
                matcher.appendReplacement(sb, "abc");
            }
            i++;
        }
        System.out.println(sb.toString());
    }

}