【发布时间】:2023-03-11 22:59:02
【问题描述】:
我正在尝试编写一个方法,该方法接受要找到的输入字符串和输入字符串来替换找到的单词的所有实例并返回所做的替换次数。我正在尝试使用 JAVA 正则表达式中的模式和匹配器。我有一个名为“text.txt”的文本文件,其中包括“这是一个测试这是一个测试这是一个测试”。当我尝试搜索“test”并将其替换为“mess”时,该方法每次都返回 1,并且没有替换任何单词 test。
public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException
{
int cnt = 0;
BufferedReader input = new BufferedReader( new FileReader(this.filename));
Writer fw = new FileWriter("test.txt");
String line = input.readLine();
while (line != null)
{
Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {matcher.replaceAll(replace); cnt++;}
line = input.readLine();
}
fw.close();
return cnt;
}
【问题讨论】:
-
您想替换文字字符串。为什么要使用正则表达式?另外,replaceAll 不返回替换的数量,那它怎么工作?
标签: java regex replaceall