对字符串的查找,剪切,替换,提取(正则表达式)

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

//对字符串的查找,剪切,替换,提取
public class StringAction {
    public static void main(String[] args) {
        StringAction sa = new StringAction();
        System.out.print(sa.action4());
    }

    public Boolean action1() {// 查询,判断某个字符串里是否有这个字符串
        String str = "abcdefgh";
        String regex = "a";
        Pattern p = Pattern.compile(regex);
        // 如果想在查找时忽略大小写,则可以写成pattern     p=pattern.compile(regex,pattern.case_insensitive);
        Matcher m = p.matcher(str);
        return m.find();
    }

    public String[] action2() {// 将一个字符串根据某个特定符号,生成数组
        String str = "xd::abc::cde";
        return str.split("::");
    }

    public String action3() {// 将一个字符串里一个或多个a的地方替换为一个a
        String regex = "a+"; // 表示一个或多个a
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher("aaabbced a ccdeaa");
        return m.replaceAll("a");
    }

    public String action4() {// 提取
        String regex = ".+\\\\(.+)$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher("c:\\dir1\\dir2\\name.txt\\a");
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }
}

posted on 2015-08-26 14:28  米虫爱喝咖啡  阅读(283)  评论(0编辑  收藏  举报

导航