如何删除任何字符串末尾的逗号

How to remove commas at the end of any string

我有字符串 "a,b,c,d,,,,, "",,,,a,,,,"

我希望将这些字符串分别转换为 "a,b,c,d"",,,,a"

我正在为此写一个正则表达式。我的 java 代码如下所示

public class TestRegx{
public static void main(String[] arg){
    String text = ",,,a,,,";
    System.out.println("Before " +text);
    text = text.replaceAll("[^a-zA-Z0-9]","");
    System.out.println("After  " +text);
}}

但是这里删除了所有逗号。

这个怎么写才能达到上面给的?

使用:

text.replaceAll(",*$", "")

正如@Jonny 在评论中提到的,也可以使用:-

text.replaceAll(",+$", "")

您的第一个示例末尾有一个 space,因此它需要匹配 [, ]。多次使用同一个正则表达式时,最好预先编译好,只需要替换一次,并且至少要去掉一个字符(+).

简单版:

text = text.replaceFirst("[, ]+$", "");

测试两个输入的完整代码:

String[] texts = { "a,b,c,d,,,,, ", ",,,,a,,,," };
Pattern p = Pattern.compile("[, ]+$");
for (String text : texts) {
    String text2 = p.matcher(text).replaceFirst("");
    System.out.println("Before \"" + text  + "\"");
    System.out.println("After  \"" + text2 + "\"");
}

输出

Before "a,b,c,d,,,,, "
After  "a,b,c,d"
Before ",,,,a,,,,"
After  ",,,,a"