在每个给定的字符后插入一个空格 - java

use*_*856 0 java regex

我需要在字符串中的每个给定字符后插入一个空格.

例如 "abc.def..."

需要成为 "abc. def. . . "

所以在这种情况下,给定的字符是点.

我在谷歌上搜索没有回答这个问题

我真的应该去获得一些严肃的正则表达式知识.

编辑:------------------------------------------------ ----------

String test = "0:;1:;";
test.replaceAll( "\\:", ": " );
System.out.println(test);

// output: 0:;1:;
// so didnt do anything
Run Code Online (Sandbox Code Playgroud)

解决方案:------------------------------------------------ -------

String test = "0:;1:;";
**test =** test.replaceAll( "\\:", ": " );
System.out.println(test);
Run Code Online (Sandbox Code Playgroud)

tan*_*ens 6

你可以使用String.replaceAll():

String input = "abc.def...";
String result = input.replaceAll( "\\.", ". " );
// result will be "abc. def. . . "
Run Code Online (Sandbox Code Playgroud)

编辑:

String test = "0:;1:;";
result = test.replaceAll( ":", ": " );
// result will be "0: ;1: ;" (test is still unmodified)
Run Code Online (Sandbox Code Playgroud)

编辑:

正如在其他答案中所说的那样,String.replace()只需要这个简单的替换.只有当它是正则表达式时(就像你在问题中所说的那样),你必须使用它String.replaceAll().