【问题标题】:Remove last comma from string that doesn't end with comma in Java 8 [duplicate]从Java 8中不以逗号结尾的字符串中删除最后一个逗号[重复]
【发布时间】:2019-01-23 04:38:04
【问题描述】:

我有输入字符串:

String myString = "test, test1, must not be null";

我想删除这个字符串中的最后一个逗号

预期输出:

test, test1 must not be null

知道这是否可以使用 StringUtils 完成吗?

【问题讨论】:

  • 下一次:显示您自己努力解决问题的问题比那些含蓄地期望其他人完成工作的“这里是要求”更受欢迎给你。

标签: java string


【解决方案1】:

这是一个使用否定前瞻来定位字符串中最后一个逗号的选项:

String myString = "test, test1, must not be null";
myString = myString.replaceAll(",(?!.*,)", "");
System.out.println(myString);

test, test1 must not be null

Demo

【讨论】:

  • 是的,但你需要 DOTALL 来处理换行符
  • @PatrickParker OP 是否提到需要跨换行符进行匹配?
  • 否,但在引入原始问题中未说明的假设(例如,不得有换行符)时值得一提。我的评论达到了这个目的,就是这样
【解决方案2】:

您也可以使用StringBuilder

String result = new StringBuilder(myString)
    .deleteCharAt(myString.lastIndexOf(",")).toString()

//"test, test1 must not be null" is the result

您可能需要将其包装在 if(myString.lastIndexOf(",") >= 0) 中以避免索引越界异常

【讨论】:

    【解决方案3】:

    使用正则表达式,您可以替换最后一个 ,,例如:

    String result = myString.replaceAll(",([^,]*)$", "$1");
    

    实质上,它会查找一个逗号,后跟 0 个或多个非逗号字符,直到字符串的末尾,然后用相同的东西替换该序列,不带逗号。

    【讨论】:

    • 这里不需要使用捕获组。
    【解决方案4】:

    这样可以正常工作:

    String myString = "test, test1, must not be null";
        int index = myString.lastIndexOf(",");
        StringBuilder sb = new StringBuilder(myString);
        if(index>0) {
            sb.deleteCharAt(index);
        }
    
        myString = sb.toString();
    
        System.out.println(myString);
    

    【讨论】:

      【解决方案5】:

      你不能在代码上游解决问题吗?不是在列表的每个元素之后添加逗号,而是将其放在列表的每个元素之前,除了第一个元素。那么你就不需要求助于这些老套的解决方案了。

      【讨论】:

      • OP 要删除的最后一个逗号不是悬空的最后一个逗号,这意味着发生了错误的连接。相反,它似乎是数据的一部分。
      【解决方案6】:

      使用Stringsubstring() 函数的另一种解决方案。

      int index=str.lastIndexOf(',');
      if(index==0) {//end case
          str=str.substring(1);
      } else {
          str=str.substring(0, index)+ str.substring(index+1);
      }
      

      【讨论】:

        【解决方案7】:

        试试这个:

        int index=str.lastIndexOf(',');
        if(index==0) {//end case
            str=str.substring(1);
        } else {
            str=str.substring(0, index)+ str.substring(index+1);
        }
        

        【讨论】:

          猜你喜欢
          • 2013-07-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-05
          • 2015-10-28
          • 2013-10-07
          • 2013-08-30
          相关资源
          最近更新 更多