简体   繁体   English

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

[英]replace all whitespace delimited strings

I am trying to replace some strings delimited by whitespace. 我试图替换由空格分隔的一些字符串。 Pattern matching works as expected but at the time of replacement the whitespace is also replaced (like newline in following example) which I want to avoid. 模式匹配按预期工作,但在替换时,空格也被替换(如下例中的换行符),我想避免。 This is what I have so far: 这是我到目前为止:

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

Match and capture the whitespace at the end of the from string, and then use it in the replacement: 匹配捕获from字符串末尾的空格,然后在替换中使用它:

String from = "foo bar";
String to = "bar foo";
myString = myString.replaceAll(from + "(\\s+)", to + "$1");
System.out.println(myString);

Note that you could also just use a single string foo bar\\\\s+ for the pattern, but maybe you don't want this, because you want the pattern to be flexible. 请注意,您也可以使用单个字符串foo bar\\\\s+作为模式,但也许您不希望这样,因为您希望模式具有灵活性。

Output: 输出:

foo bar,
is a special string composed of bar foo and
it is bar foo
is indeed special!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM