【问题标题】:How to remove commas at the end of any string如何删除任何字符串末尾的逗号
【发布时间】:2015-08-28 04:49:41
【问题描述】:

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

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

如上给出的如何写这个来实现?

【问题讨论】:

    标签: java regex string str-replace


    【解决方案1】:

    使用:

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

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

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

    【讨论】:

    • 你不需要使用()捕获,
    • @TheLostMind 编辑了我的答案,感谢您的评论。
    • + 量词代替* 怎么样
    • @Jonny,编辑了答案。
    • 第一个字符串"a,b,c,d,,,,, " 末尾有空格,所以这段代码不起作用。
    【解决方案2】:

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

    简单版:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 2012-05-20
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      相关资源
      最近更新 更多