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("读取完毕!");
        }

    运行结果:

  • 相关阅读:
    牛顿迭代法
    C语言补遗
    Manjaro添加开机启动脚本
    tensorboard查看pytorch模型
    Kindle最佳排版记录
    01背包问题详解
    差分法介绍
    BFS详解
    UVA11732 "strcmp()" Anyone?
    LA3942 Remember the Word
  • 原文地址:https://www.cnblogs.com/don9/p/7009985.html
Copyright © 2011-2022 走看看