Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove commas at the end of any string

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

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

I am writing a regular expression for this. My java code looks like this

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 the commas here.

How can write this to achieve as given above?

like image 704
bpbhat77 Avatar asked Dec 10 '22 21:12

bpbhat77


2 Answers

Use :

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

As mentioned by @Jonny in comments, can also use:-

text.replaceAll(",+$", "")
like image 69
Amit Bhati Avatar answered Dec 28 '22 08:12

Amit Bhati


Your first example had a space at the end, so it needs to match [, ]. When using the same regular expression multiple times, it's better to compile it up front, and it only needs to replace once, and only if at least one character will be removed (+).

Simple version:

text = text.replaceFirst("[, ]+$", "");

Full code to test both inputs:

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 + "\"");
}

Output

Before "a,b,c,d,,,,, "
After  "a,b,c,d"
Before ",,,,a,,,,"
After  ",,,,a"
like image 26
Andreas Avatar answered Dec 28 '22 08:12

Andreas