0

I need to ask you something, about my problem.Try to imagine, that a have a string like: "23221323,213213,123213,,,"

I have been looking in several websites, but i dont find anything. I need a regular expression about how to remove the character(,) ..

I mean, i want to remove the last , if its more that 1:

Example:

"2323,3434,2332" ==> its OK

"3434,21321,45454,,,,==> BAD. you have to remove the last 3 , only 1 final is allowed.

Actually i have something in java, that works:

  String sCadena="asd,";
            CharSequence cs1 = ",,";
            CharSequence cs2 = ",,,";
            CharSequence cs0 = ",";

            if(sCadena.contains(cs2)){
                sCadena=sCadena.substring(0, sCadena.length() - 3);
            }


             else if (sCadena.contains(cs1)){
                sCadena=sCadena.substring(0, sCadena.length() - 2);
            }


             else if  (sCadena.contains(cs0)){
                sCadena=sCadena.substring(0, sCadena.length() - 1);
            }



}       

But i want to make a regular expression to avoid this, because if the user enter a lot of (,), i have to implement more if to control this....

Any ideas??

Dekker
  • 85
  • 2
  • 10

1 Answers1

1

This should work for you :

public static void main(String[] args) {
    String s = "23221323,213213,123213,,,";
    s = s.replaceAll(",+$",","); // replaces all trailing commas with a single one
    System.out.println(s);
    }

O/P :

23221323,213213,123213,

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Thats it, thanks buddy. This is exactly what i need: String s = "23221323,213213,123213,,,,,,,,,,"; s = s.replaceAll(",+$"," "); // replaces all trailing commas with a single one System.out.println(s); Your funcion but the second parameter has to be blank. really thanks TheLostMind – Dekker Apr 06 '16 at 14:52
  • You need one comma at the end right? @Dekker.. Or do you want to remove all commas at the end? – TheLostMind Apr 06 '16 at 14:54
  • Its all right, i have all that i need TheLostMind: this is the function that i need. Thanks: String s = "23221323,213213,123213,,,,,,,,,,,,,"; s = s.replaceAll(",+$"," "); // replaces all trailing commas with a single one System.out.println(s); – Dekker Apr 06 '16 at 15:05