英文:
Java: how to replace space and \r in string with delimiter value?
问题
如何用分隔符替换字符串中的空格和 \r ?
String oldDelimiter = " ";
String newDelimiter = "o";
String fileContent = "try some random %!(chars)!% ##\r" +
"or line break$@ \r" +
":(";
fileContent = fileContent.replaceAll("[" + oldDelimiter + "]+", newDelimiter);
fileContent = fileContent.replaceAll("\r", newDelimiter);
当前输出:`tryosomeo**random**o%!(chars)!%o##oorolineobreak$@oo:(`
期望输出:`tryosomeo**random**o%!(chars)!%o##oorolineobreak$@o:(`
请注意,在 `@` 符号后面的字符串末尾有额外的字母 `o`。
更新:只有在出现 `space` 或 `\r` 时才应替换为 `o`。但是,如果 `space` 和 `\r` 彼此相邻,则只替换为一个 `o` 分隔符。
<details>
<summary>英文:</summary>
How to replace space and \r in string with delimiter value?
String oldDelimiter = " ";
String newDelimiter = "o";
String fileContent = "try some random %!(chars)!% ##\r" +
"or line break$@ \r" +
":(";
fileContent = fileContent.replaceAll("[" + oldDelimiter + "]+", newDelimiter);
fileContent = fileContent.replaceAll("\r", newDelimiter);
current output: `tryosomeo**random**o%!(chars)!%o##oorolineobreak$@oo:(`
desired output: `tryosomeo**random**o%!(chars)!%o##oorolineobreak$@o:(`
Notice the extra letter `o` towards the end of the string after the `@` symbol.
Update: it should only replace with o if there is a `space` or `\r`. However, if both `space` and `\r` and next to each other, then only replace with one `o` delimiter.
</details>
# 答案1
**得分**: -2
像安德烈亚斯所说,使用“[ \r]”来替换所有的\r和“ ”为空格。
fileContent = fileContent.replaceAll(" [ \r]+", "o");
<details>
<summary>英文:</summary>
Like Andreas said, use the "[ \r]" to replace all of the \r and " " with spaces.
fileContent = fileContent.replaceAll("[ \r]+", "o");
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论