2017-04-06 8 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! 
関連する問題