替换所有以空格分隔的字符串
问题描述:
我试图替换一些由空格分隔的字符串。模式匹配按预期工作,但在替换时,空白也被替换(如下面的例子中的换行符),这是我想避免的。这是我到目前为止有:替换所有以空格分隔的字符串
String myString = "foo bar,\n"+
"is a special string composed of foo bar and\n"+
"it is foo bar\n"+
"is indeed special!";
String from = "foo bar";
String to = "bar foo";
myString = myString.replaceAll(from + "\\s+", to)
expected output = "foo bar,
is a special string composed of bar foo and
it is bar foo
is indeed special!";
actual output = "foo bar,
is a special string composed of bar foo and
it is bar foo is indeed special!";
答
比赛和捕捉空白在from
字符串的结尾,然后用它替换:
String from = "foo bar";
String to = "bar foo";
myString = myString.replaceAll(from + "(\\s+)", to + "$1");
System.out.println(myString);
请注意,你也可以只是使用单个字符串foo bar\\s+
作为模式,但也许你不想要这样,因为你希望模式是灵活的。
输出:
foo bar,
is a special string composed of bar foo and
it is bar foo
is indeed special!