简体   繁体   English

replaceAll粘贴部分不必要的额外字符串

[英]replaceAll pastes part of unnecessary extra string

This is my example java code: 这是我的示例java代码:

String oldContent = "Book 1;Author 1;11|11\n" +
        "Book 2;Author 2;1|1\n" +
        "Book 3;Author 3;1|1\n" +
        "Book 4;Author 4;1|1\n" +
        "Book 5;Author 5;1|1\n";

String old = "Book 1;Author 1;11";
String newS = "Book 1;Author 1;12|12";

String content = oldContent.replace(old,newS);

System.out.println(content);

I'm trying to update part of String in oldContent (old) with new part of string (newS). 我正在尝试使用string(newS)的新部分更新oldContent(旧)中的部分String。 The result should be: 结果应该是:

Book 1;Author 1;12|12
Book 2;Author 2;1|1
Book 3;Author 3;1|1
Book 4;Author 4;1|1
Book 5;Author 5;1|1

but actually is: 但实际上是:

Book 1;Author 1;12|12|11
Book 2;Author 2;1|1
Book 3;Author 3;1|1
Book 4;Author 4;1|1
Book 5;Author 5;1|1

with these extra |11 . 这些额外的|11 Could someone explain me how it works and why? 有人可以解释一下它是如何工作的,为什么? I have been trying with replace() , replaceAll() but result is the same. 我一直在尝试使用replace()replaceAll()但结果是一样的。

You are replacing Book 1;Author 1;11|11 sequence with Book 1;Autor 1;12|12 sequence however the first line ends with 1:11|11 . 您正在替换Book 1;Author 1;11|11序列与Book 1;Autor 1;12|12序列,但第一行以1:11|11 Notice the extra |11 at the end of a line, it won't be processed and will be appended to Book 1;Autor 1;12|12 . 注意一行末尾的额外|11 ,它将不会被处理并将附加到Book 1;Autor 1;12|12

To fully replace first line you need: 要完全替换您需要的第一行:

String old = "Book 1;Autor 1;11|11";
String newS = "Book 1;Autor 1;12|12";
String content = oldContent.replace(old, newS);

Pay attention! 请注意! You have typo in Author word: 你在Author词中有拼写错误:

String old = "Book 1;Author 1;11|11";
String newS = "Book 1;Author 1;12|12";
String content = oldContent.replace(old, newS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM