替换所有空格分隔的字符串

时间:2017-04-06 07:59:37

标签: java regex string

我正在尝试替换由空格分隔的一些字符串。模式匹配按预期工作,但在替换时,空格也被替换(如下例中的换行符),我想避免。这就是我到目前为止所做的:

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!";

1 个答案:

答案 0 :(得分:0)

匹配捕获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!