使用replaceFirst()替换String的内容

时间:2016-03-21 05:19:12

标签: java regex string replace

我的文件包含以下内容:

Test:Line1@line.com
Goal:[[goal]]
Email:[[email]]
Further Text

下面是将文件内容放入StringBuffer并将值输入String output的代码。

Path signature = Paths.get("signature.txt");
StringBuffer sigBuffer = new StringBuffer();
String line = null;
BufferedReader reader = null;
try {
 reader = Files.newBufferedReader(signature);
 while ((line = reader.readLine()) != null) {
   sigBuffer.append(line);
   sigBuffer.append("\n");
 }
 String output = sigBuffer.toString();
} catch...finally...

我想将[[goal]]替换为Goal A[[email]]email@mail.com

我试过了:

String regExp = "\\[\\[[a-z_]*\\]\\]";
output.replaceFirst(regExp, "Goal A");
output.replaceFirst(regExp, "email@mail.com");

但我的输出仍然是:

Test:Line1@line.com
Goal:[[goal]]
Email:[[email]]
Further Text

1 个答案:

答案 0 :(得分:2)

字符串是不可变的。您需要将replaceFirst调用的结果分配回变量。

output = output.replaceFirst(....)