如何在Java中形成正则表达式,以便能够将匹配的数据直接存储为XML?
答案 0 :(得分:1)
我会使用包装文本文件的Scanner类来实现。然后,使用适当的正则表达式创建Pattern对象。然后,您将能够将Pattern对象提供给Scanner实例并找到每个目标数据。最后,为了将这些数据保存为XML,我会使用JAXB来限制内存占用,因为您可能事先不知道有多少数据需要保存为XML。
答案 1 :(得分:0)
使用类似
的内容public CharSequence fromFile(String filename) throws IOException {
FileInputStream input = new FileInputStream(filename);
FileChannel channel = input.getChannel();
// Create a read-only CharBuffer on the file
ByteBuffer bbuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, (int)channel.size());
CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
return cbuf;
}
并比较为:
try {
// Create matcher on file
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher(fromFile("yourFile.txt"));
// Find all matches
while (matcher.find()) {
// Get the matching string
String match = matcher.group();
}
} catch (IOException e) {
}