Java多行代码替换文件中的多个实例
问题描述:
好的,所以我一直在寻找几个小时来解决我的问题,但似乎没有出现。 因此,这里是我的代码段,然后问题:Java多行代码替换文件中的多个实例
Pattern forKeys = Pattern.compile("^<feature>\\s*<name>Deviation</name>.*?</feature>", Pattern.DOTALL|Pattern.MULTILINE);
Matcher n = forKeys.matcher("");
String aLine = null;
while((aLine = in.readLine()) != null) {
n.reset(aLine);
String result = n.replaceAll("");
out.write(result);
out.newLine();
}
就让我们假设未声明的变量已经声明..
我要说的是,我的正则表达式(可能的匹配也)不能正常工作。
我想用“<feature><name>Deviation</name>*any character/s here*</feature>
”包括在FF线的擦除部分:
<feature>
<name>Deviation</name>
<more words here>
</feature>
<feature>
<name>Average</name>
</feature>
<feature>
<name>Deviation</name>
sample words
</feature>
我想我的问题是使用repititive运营商(如何遍历换行符,制表符等)但我似乎无法找到正确的表达方式。
任何想法?提前致谢。
答
Parsing HTML or XML with regex是evil and error-prone。
使用XML解析器,事情会更好。
下面是使用Dom4J你的问题的解决方案:
// parse XML source
Document document = DocumentHelper.parseText(yourXmlText);
Iterator<Element> featureIterator =
// get an iterator for all <feature> elements
document.getRootElement().elementIterator("feature");
while(featureIterator.hasNext()){
Element featureElement = featureIterator.next();
// if <feature> has a child <name> with Content "Deviation"
if("Deviation").equals(featureElement.elementTextTrim("name")){
// remove this <feature> element
featureIterator.remove();
}
}
// write modified XML back to file
new XMLWriter(
new FileOutputStream(yourXmlFile), OutputFormat.createPrettyPrint()
).write(document);
除此之外,你也犯了一个错误(见我的意见):
// aLine is just a single line
while((aLine = in.readLine()) != null) {
n.reset(aLine);
// yet you want to replace a multi-line pattern
String result = n.replaceAll("");
out.write(result);
out.newLine();
}
你的正则表达式可能会或可能无法正常工作如果您将整个文件读取到一个字符串中,但如果将其应用于单独的行上,则它无法工作。
感谢您的快速回复!我会研究你的建议,因为XML解析器还没有进入我的脑海(我对Java的使用经验不足,所以知识有限)。一旦我解决了我的问题,会让你知道。再次感谢! – legaicy 2011-03-17 02:02:23
只是一个后续。我研究了XML解析,而不是使用你的建议,我尝试了DOM并且它可以无缝工作!感谢您给我正确的想法。 :) – legaicy 2011-03-17 09:36:36
@legaicy很高兴帮助! – 2011-03-17 09:38:36