Java split string on third comma

2020-07-26 14:00发布

问题:

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.

回答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:

  • How to find nth occurrence of character in a string?


回答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"]



回答3:

You can use this regex:

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

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