2017-04-06 49 views
1

我試圖替換一些由空格分隔的字符串。模式匹配按預期工作,但在替換時,空白也被替換(如下面的例子中的換行符),這是我想避免的。這是我到目前爲止有:替換所有以空格分隔的字符串

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

回答

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! 
相關問題