【问题标题】:Java Regex remove new lines, but keep spaces.Java Regex 删除新行,但保留空格。
【发布时间】:2018-11-28 20:00:15
【问题描述】:

对于字符串" \n a b c \n 1 2 3 \n x y z ",我需要它变成"a b c 1 2 3 x y z"

使用这个正则表达式 str.replaceAll("(\s|\n)", "");我可以得到“abc123xyz”,但我怎样才能得到中间的空格。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您不必使用正则表达式;您可以改用trim()replaceAll()

     String str = " \n a b c \n 1 2 3 \n x y z ";
     str = str.trim().replaceAll("\n ", "");
    

    这将为您提供您正在寻找的字符串。

    【讨论】:

    • @pmartin8 想告诉对此感到满意的 OP 吗?
    【解决方案2】:

    这将删除所有空格和换行符

    String oldName ="2547 789 453 ";
    String newName = oldName.replaceAll("\\s", "");
    

    【讨论】:

      【解决方案3】:

      这将起作用:

      str = str.replaceAll("^ | $|\\n ", "")
      

      【讨论】:

        【解决方案4】:

        如果你真的想用正则表达式来做这件事,这可能会为你解决问题

        String str = " \n a b c \n 1 2 3 \n x y z ";
        
        str = str.replaceAll("^\\s|\n\\s|\\s$", "");
        

        【讨论】:

          【解决方案5】:

          这是一个非常简单明了的示例,说明我将如何做到这一点

          String string = " \n a   b c \n 1  2   3 \n x y  z "; //Input
          string = string                     // You can mutate this string
              .replaceAll("(\s|\n)", "")      // This is from your code
              .replaceAll(".(?=.)", "$0 ");   // This last step will add a space
                                              // between all letters in the 
                                              // string...
          

          您可以使用此示例来验证最后一个正则表达式是否有效:

          class Foo {
              public static void main (String[] args) {
                  String str = "FooBar";
                  System.out.println(str.replaceAll(".(?=.)", "$0 "));
              }
          }
          

          输出:“F o o B a r”

          更多关于正则表达式环视的信息:http://www.regular-expressions.info/lookaround.html

          这种方法使它适用于任何字符串输入,并且它只是在您的原始工作上增加了一个步骤,以准确回答您的问题。快乐编码:)

          【讨论】:

            猜你喜欢
            • 2018-03-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-10
            • 1970-01-01
            • 2014-12-11
            • 1970-01-01
            • 2011-03-19
            相关资源
            最近更新 更多