gpt4 book ai didi

java - Java中使用matcher.replaceall替换文件中所有匹配的字符串

转载 作者:行者123 更新时间:2023-12-01 13:49:01 24 4
gpt4 key购买 nike

我正在尝试使用 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中的最后一个字符串进行更新。每次我都用新匹配的字符串覆盖该字符串。我怎样才能得到最终的大字符串,它是用所有匹配的字符串(模式列表中的名称)更新的。

最佳答案

我相信你有很多冗余代码。您绝对不需要 Pattern 对象列表。

考虑这段代码:

String output = new Scanner(new File("C:/file.in")).useDelimiter("\\Z").next();
String repl = output.replaceAll("\b(Shannon|Sperling|Kim|Tammy|Nancy|Lana)\b",
<span style='background-color:red;'>$1</span>");

File file = new File("C:/data/filename.in");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write( repl );
bw.close();

关于java - Java中使用matcher.replaceall替换文件中所有匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20116903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com