【发布时间】:2013-11-21 09:23:50
【问题描述】:
我正在尝试使用matcher.replaceAll()替换文件中的仅匹配的字符串。如下所示
public static void main(String[] args) throws IOException, BadLocationException {
FileInputStream fis = null;
String output = new Scanner(new File("C:/file.in")).useDelimiter("\\Z").next();//file.in contains HTML text
String s2 = null;
StringWriter writer = new StringWriter();
for (int i=0; i<patternList.size(); i++)//PatternList contains names to be extracted from file
{
Matcher matcher = patternList.get(i).matcher(output);
while (matcher.find())
{
String matched = matcher.group();//I need to replace only matched strings returned by matcher
s2=matcher.replaceAll("<span style='background-color:red;'>"+matched+"</span>");
File file = new File("C:/data/filename.in");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s2);
bw.close();
}
}
结果字符串s2 仅更新了 PatternList 中的最后一个字符串。每次我用新匹配的字符串覆盖字符串。如何获得使用所有匹配字符串(模式列表中的名称)更新的最终大字符串。
【问题讨论】: