Anuj
Anuj

Reputation: 408

Use regex to remove unwanted commas

I am creating an app in which I have generated string like this:

 hihibjj,,,,,,,ghjjjj, , ,[email protected],,,,[email protected], [email protected], [email protected]

What I want is to delete unwanted commas, only single comma separated values should be present.

Code that I have tried

for (int i = 0; i < temp.length; i++) {
  for (int j = 0; j < emailSeperated.size(); j++) {
    if (temp[i].trim().equals(emailSeperated.get(j).trim())) {
      strEmailValue = strEmailValue.replace(temp[i], "").trim();
      Log.e("strEmail trimmed value", strEmailValue);
    } else if (temp[i].trim().equals(emailSeperated.get(j).trim())) {
      strEmailValue = strEmailValue.replaceAll(temp[i] + ",", "").trim();
    }
  }
} 

Upvotes: 4

Views: 191

Answers (3)

mirmdasif
mirmdasif

Reputation: 6354

String as = "as,,,,,,";
as= as.replaceAll(",,+",",");

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174844

You could use lookbehind also.

Regex:

(?<=,) ?,

Replacement string:

Empty string

DEMO

System.out.println("hihibjj,,,,,,,ghjjjj, , ,[email protected],,,,[email protected], [email protected], [email protected]".replaceAll("(?<=,) ?,", ""));

Output:

hihibjj,ghjjjj,[email protected], [email protected], [email protected], [email protected] 

Upvotes: 0

Toto
Toto

Reputation: 91518

Just find: ,,+ and replace with: ,

Upvotes: 7

Related Questions