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

4

我有字符串"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);
}}

但是这会移除这里的所有逗号。

如何编写以实现上述所示?

2个回答

9

使用:

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

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

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

你不需要使用 () 来捕获 , - TheLostMind
1
@TheLostMind 我已经编辑了我的答案,感谢您的评论。 - Amit Bhati
1
使用 + 量词代替 * 量词怎么样? - Jonny 5
@Jonny,已编辑答案。 - Amit Bhati
第一个字符串 "a,b,c,d,,,,, " 在末尾有空格,所以这段代码无法工作。 - Andreas

4
你的第一个示例末尾有一个空格,因此需要与[, ]相匹配。当多次使用同一正则表达式时,最好提前编译它,并且仅在至少删除一个字符(+)时替换一次。
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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接