How to remove commas at the end of any line

I have a line "a,b,c,d,,,,, ",",,,,a,,,,"

I want these strings to be converted to "a,b,c,d"and ",,,,a"accordingly.

I am writing a regular expression for this. My Java code is as follows:

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

But this is removing all commas here.

How can this be written as indicated above?

+4
source share
2 answers

Using:

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

As mentioned in @Jonny's comments, you can also use: -

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

, [, ]. , , (+).

:

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"
+4

All Articles