简体   繁体   中英

Use regex to remove unwanted commas

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

 hihibjj,,,,,,,ghjjjj, , ,kartik.isworking@gmail.com,,,,karan.adep@gmail.com, android-developer-support@google.com, prerna.mungekar@hamarisuraksha.com

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

只需找到: ,,+并替换为: ,

You could use lookbehind also.

Regex:

(?<=,) ?,

Replacement string:

Empty string

DEMO

System.out.println("hihibjj,,,,,,,ghjjjj, , ,kartik.isworking@gmail.com,,,,karan.adep@gmail.com, android-developer-support@google.com, prerna.mungekar@hamarisuraksha.com".replaceAll("(?<=,) ?,", ""));

Output:

hihibjj,ghjjjj,kartik.isworking@gmail.com, karan.adep@gmail.com, android-developer-support@google.com, prerna.mungekar@hamarisuraksha.com 
String as = "as,,,,,,";
as= as.replaceAll(",,+",",");

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