Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Javascript (https://www.askmehelpdesk.com/forumdisplay.php?f=452)
-   -   Split a string with comma neglecting commas inside special characters (https://www.askmehelpdesk.com/showthread.php?t=808356)

  • Feb 17, 2015, 05:38 AM
    preethyb
    Split a string with comma neglecting commas inside special characters
    For this given input


    dog(dog1,dog2,dog3),cat{cat1,cat2,cat3},pe^t"pet1, pet2,pet3",pi*g[pig1,pig2,pig3]


    I want the output as
    dog(dog1,dog2,dog3)
    cat{cat1,cat2,cat3}
    pe^t"pet1,pet2,pet3"
    pi*g[pig1,pig2,pig3]


    I tried the following


    Code:

    String str = "dog(dog1,dog2),cat{cat1,cat2},pe^t\"pet1,pet2\",pi*g[pig1,pig2]";
    if (str.contains(",")) {
      String arry[] = str.split(",(? \\w+[})\\]\\\"])");
      int len = arry.length;
      for (int i = 0; i < len; i++) {
          if(arry[i].startsWith("\""))
          {
            System.err.println(arry[i].replaceAll("^\"|\"$", "").trim());
          }
          else{
            System.err.println(arry[i].trim());
          }
      }
    }


    But it will work only for when there are two strings between specialcharacters like the following
    "dog(dog1,dog2),cat{cat1,cat2},pe^t\"pet1,pet2\",p i*g[pig1,pig2]"

  • All times are GMT -7. The time now is 06:34 PM.