需求:获取一个本地文件中所有符合 $[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("读取完毕!");
}

运行结果:

java正则表达式匹配文本中想要的字符串-LMLPHP

04-28 19:37