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+"\r\n");
        }
        
        br.close();
        bw.close();
        
        System.out.println("读取完毕!");
    }

运行结果:

 

转载于:https://www.cnblogs.com/don9/p/7009985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值