【问题标题】:How to remove space after the decimal point without removing other spaces?如何删除小数点后的空格而不删除其他空格?
【发布时间】:2021-06-15 20:46:22
【问题描述】:

我有一个String,它在单个字符串中有多个值。我只想删除小数点后的空格而不删除字符串中的其他空格。

String testString = "EB:3668. 19KWh DB:22. 29KWh";

testString = testString.trim();
String beforeDecimal = testString.substring(0, testString.indexOf("."));
String afterDecimal = testString.substring(testString.indexOf("."));

afterDecimal = afterDecimal.replaceAll("\\s+", "");

testString = beforeDecimal + afterDecimal;

textView.setText(testString);

在我的字符串中,单个字符串中有两个值 EB:3668. 19KWhDB:22. 29KWh。 我只想删除小数点后的空格并将String 设为这样:

EB:3668.19KWh DB:22.29KWh

【问题讨论】:

    标签: java string text replace textview


    【解决方案1】:

    您可以使用 2 个捕获组并匹配它们之间的空间。在替换中使用没有空格的 2 组。

    (\d+\.)\h+(\d+)
    

    Regex demo

    String testString="EB:3668. 19KWh DB:22. 29KWh";
    String afterDecimal = testString.replaceAll("(\\d+\\.)\\h+(\\d+)","$1$2");
    System.out.println(afterDecimal);
    

    输出

    EB:3668.19KWh DB:22.29KWh
    

    或者更具体的模式可能包括 KWh:

    \b(\d+\.)\h+(\d+KWh)
    

    Regex demo

    【讨论】:

      【解决方案2】:

      只需使用string.replaceAll("\\. ", ".");

      感谢 Henry 指出我必须逃离 .

      【讨论】:

        【解决方案3】:

        我现在不在编辑器面前,但是您不能在一行中使用 replaceAll 方法来完成此操作,而不会破坏它吗?

        var text = testString.replaceAll(". ", ".");
        

        【讨论】:

        • 您会对此效果感到惊讶。另请参阅 mindoverflow 的答案。
        • 啊,不错。这就是我想用编辑器测试它的原因:D
        【解决方案4】:

        您可以删除小数点小数部分之间不必要的空格,如下所示。此代码还删除了其他额外的空格:

        String testString = " EB:3668. 19KWh   DB:22. 29KWh ";
        
        String test2 = testString
                // remove leading and trailing spaces
                .trim()
                // replace non-empty sequences of space
                // characters with a single space
                .replaceAll("\\s+", " ")
                // remove spaces between the decimal
                // point and the fractional part
                // regex groups:
                // (\\d\\.) - $1 - digit and point
                // ( )      - $2 - space
                // (\\d)    - $3 - digit
                .replaceAll("(\\d\\.)( )(\\d)", "$1$3");
        
        System.out.println(test2); //EB:3668.19KWh DB:22.29KWh
        

        另见:How do I remove all whitespaces from a string?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-29
          • 2021-04-13
          • 2019-04-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-15
          相关资源
          最近更新 更多