zoukankan      html  css  js  c++  java
  • java正则表达式匹配文本中想要的字符串

    需求:获取一个本地文件中所有符合 $[MAKE_PACKAGE] 格式的字符串,并输出到另一个文件中.

    public static void main(String[] args) throws Exception {
            
            loadVar("src/cn/don9/templates/Action.txt","src/cn/don9/templateVar/SysActionVar.txt");
            
        }
        
        public static void loadVar(String infilePath,String outfilePath) throws Exception{
            //定义set集合,实现去重效果
            Set<String> result = new HashSet<String>();
            //定义正则表达式
            String regex = "[\$][\[]\w+[\]]";
            Pattern pattern = Pattern.compile(regex);
            
            //读取文件
            File file = new File(infilePath);
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while((line=br.readLine())!=null){
                //匹配文本中每行的字符串
                Matcher matcher = pattern.matcher(line);
                //发现匹配的字符串,存入set中
                while(matcher.find()){
                    result.add(matcher.group());
                }
            }
            
            //加载输出文件
            File outfile = new File(outfilePath);
            BufferedWriter bw = new BufferedWriter(new FileWriter(outfile));
            for(String var:result){
                //写入字符串
                bw.write(var+"
    ");
            }
            
            br.close();
            bw.close();
            
            System.out.println("读取完毕!");
        }

    运行结果:

  • 相关阅读:
    LINQ中selectManay操作符(五)
    LINQ中select操作符(四)
    高效并发进阶-白银
    JVM回收算法
    一个类是怎么被JVM执行的
    一纸理解JVM
    单例模式
    深入理解Spring AOP思想
    深入理解Spring IOC工作原理
    HashMap扩容全过程
  • 原文地址:https://www.cnblogs.com/don9/p/7009985.html
Copyright © 2011-2022 走看看