【发布时间】:2018-01-29 16:01:00
【问题描述】:
我必须准备一个使用多个正则表达式的程序。 下面是程序,但对于每个新元素,我必须初始化新的 Pattern 和 Matcher。有没有我可以在这个程序中使用的优化方式或我可以在这个程序中使用的循环。 目前在程序中,它读取文件并分配字符串中的所有 XML 标记。该文件有多个标签,我必须以 CSV 格式初始化和打印这些标签,并且文件包含大量数据,例如 GB。 有什么办法可以优化下面的代码。
正则表达式程序:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
/**
*
* @author ????
*/
import java.io.*;
import java.util.ArrayList;
import java.util.regex.*;
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
File fileToBeModified = new File("C:\\Documents\\audit.log");
String str = "";
try {
BufferedReader in = new BufferedReader(new FileReader(fileToBeModified));
StringBuffer output = new StringBuffer();
String st;
while ((st=in.readLine()) != null) {
output.append(st);
output.append('\n');
}
str = output.toString();
in.close();
}
catch (Exception fx) {
}
String usr = "";
String origin = "";
String dt = "";
String operation = "";
Pattern p = Pattern.compile("<AuditEntry>(.*\\R)*?<\\/AuditEntry>");
Matcher m = p.matcher(str);
while (m.find()) {
Pattern e = Pattern.compile("<User>(.*)</User>");
Matcher f = e.matcher(m.group(0));
while(f.find())
{
usr = f.group(1);
}
Pattern g = Pattern.compile("<Origin>(.*)</Origin>");
Matcher h = g.matcher(m.group(0));
while(h.find())
{
origin = h.group(1);
}
Pattern i = Pattern.compile("<DateTime.*\">(.*)</DateTime>");
Matcher j = i.matcher(m.group(0));
while(j.find())
{
dt = j.group(1);
}
Pattern k = Pattern.compile("Operation=\"([a-zA-z]+)\"");
Matcher l = k.matcher(m.group(0));
while(l.find())
{
operation = l.group(1);
}
System.out.println(usr+","+origin+"," +dt+ ","+operation);
}
}
}
【问题讨论】:
-
创建
的 hashmap,其中 String 是相同的标识符,现在在您的 main 方法中初始化 hashmap,并在整个代码中使用它。 -
不要使用正则表达式解析标记。
-
我无法理解为什么人们会否决一个显然来自编程初学者的问题,它提供了一个清晰的问题和格式良好的源代码,其中有人已经尝试了很多来获得解决方案。 (抱歉跑题了。)
标签: java regex pattern-matching matcher