删除字符串之间的空格

时间:2017-06-21 20:33:41

标签: java regex

我有一个字符串" parent / child1 / child2"。我希望将其输出为" parent / child1 / child2"删除其间的空白区域。

我是按照以下方式做的。我怎么能用lambda表达式来做呢?

String absoluteName = "";
for(String name : Parent.getNames.split("/")) {
    if(absoluteName.equals("")) {
       absoluteName = name.trim();
    } else {
       absoluteName += "/" + name.trim();
    }
}

不能使用.replaceAll("\\s+", "")),就像我的用例" parent / child1 / child2"和" pa rent / ch ild1 / ch ild2"被视为2个不同的值。

输入 - >输出

parent / child1 / child2 - > parent/child1/child2

pa rent / ch ild1 / ch ild2 - > pa rent/ch ild1/ch ild2

1 个答案:

答案 0 :(得分:4)

你不需要这里的lambdas。只需将/和空格仅替换为/

str = str.replace("/ ", "/");

或者如果/之后可以有更多空格要删除

str = str.replaceAll("/\\s+", "/");

更新:如果要删除/周围的所有空格,可以使用

str = str.replaceAll("\\s*/\\s*", "/");

*量词允许\\s(空白)出现零次或多次。这意味着"\\s*/\\s*"将匹配并替换

等部分
  • " /"" /"
  • "/ ""/ "
  • 或上述案例" / "" / "
  • 的组合

它也会匹配单个/,但将其替换为相同的/不会导致任何问题。

相关问题