Java split string on third comma

10,627

Solution 1

If you're simply interested in splitting the string at the index of the third comma, I'd probably do something like this:

String s = "from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234";

int i = s.indexOf(',', 1 + s.indexOf(',', 1 + s.indexOf(',')));

String firstPart = s.substring(0, i);
String secondPart = s.substring(i+1);

System.out.println(firstPart);
System.out.println(secondPart);

Output:

from:09/26/2011,type:all,to:09/26/2011
field1:emp_id,option1:=,text:1234

Related question:

Solution 2

a naive implementation

public static String[] split(String s)
{
    int index = 0;
    for(int i = 0; i < 3; i++)
        index = s.indexOf(",", index+1);

    return new String[] {
            s.substring(0, index),
            s.substring(index+1)
    };
}

This does no bounds checking and will throw all sorts of lovely exceptions if not given input as expected. Given "ABCD,EFG,HIJK,LMNOP,QRSTU" returns ["ABCD,EFG,HIJK","LMNOP,QRSTU"]

Solution 3

You can use this regex:

^([^,]*,[^,]*,[^,]*),(.*)$

The result is then in the two captures (1 and 2), not including the third comma.

Share:
10,627
pm13
Author by

pm13

Updated on June 14, 2022

Comments

  • pm13
    pm13 almost 2 years

    I have a string that I need to be split into 2. I want to do this by splitting at exactly the third comma.

    How do I do this?

    Edit

    A sample string is :

    from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234
    

    The string will keep the same format - I want everything before field in a string.