简体   繁体   中英

Regular Expression for characters ,

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??

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM