从不使用';在Java8中,t以逗号结尾

从不使用';在Java8中,t以逗号结尾,java,string,Java,String,我有输入字符串: String myString = "test, test1, must not be null"; 我想删除此字符串中的最后一个逗号 预期产出: test, test1 must not be null 您知道是否可以使用StringUtils完成此操作吗?这里有一个选项,它使用一个负向前看来定位字符串中的最后一个逗号: String myString = "test, test1, must not be null"; myString = myString.repla

我有输入字符串:

String myString = "test, test1, must not be null";
我想删除此字符串中的最后一个逗号

预期产出:

test, test1 must not be null

您知道是否可以使用StringUtils完成此操作吗?

这里有一个选项,它使用一个负向前看来定位字符串中的最后一个逗号:

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

test, test1 must not be null

您也可以使用
StringBuilder

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

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

如果(myString.lastIndexOf(“,”>)=0,您可能需要将其包装在
为了避免索引越界异常

使用正则表达式,您可以使用以下示例替换最后的

String result = myString.replaceAll(",([^,]*)$", "$1");
实际上,它查找逗号,后跟0个或多个非逗号字符,直到字符串结束,并用相同的东西替换该序列,而不使用逗号。

这将很好:

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);

你不能在代码上游解决这个问题吗?不要在列表的每个元素后面添加逗号,而是将它放在列表的每个元素前面,第一个元素除外。然后您就不需要求助于这些黑客解决方案。

使用
String
class
substring()
函数的另一种解决方案

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

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

这里不需要使用捕获组。是的,但您需要DOTALL来处理newlines@PatrickParkerOP是否提到了跨换行符匹配的必要性?没有,但在引入原始问题中未说明的假设(例如,不得有换行符)时值得一提。我的评论就是为了达到这个目的,只是为了下一次:那些表明你自己努力解决问题的问题比那些暗示希望其他人为你工作的“以下是要求”更受欢迎。OP想要删除的最后一个逗号不是悬而未决的最后一个逗号,这意味着发生了错误的连接。相反,它似乎是数据的一部分。