Reputation: 97
I want to split a string by comma, but I want the comma between the brackets are ignored.
For example:
Input:
a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6
Output:
a1:b1
a2:b2
[a3:b3-c3, b4, b5]
a4:b6
Thank you for your help in advance.
Upvotes: 0
Views: 208
Reputation: 8355
You will have to parse char-by-char in order to be precise, else you can do a hack like this:
(pseudo-code)
1. replace all brackets by (distinct) dummy placeholders (the format will depend on your context)
2. split the (new) string by the (remaining) commas (st.split(","))
3. re-replace the distinct placeholders with the original brackets values (you will have to store them somewhere) (foreach placeholder: st = st.replace(placeholder, bracket);)
Note: On step 1, you dont replace placeholders manualy, you use a regex (e.g /[[^]]+]/
) to replace the brackets by placeholders (and store them as well), and then replace back in step 3.
Example:
input:
a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6
step1: intermediate output:
a1:b1, a2:b2, __PLACEHOLDER1_, a4:b6
step2: intermediate output:
a1:b1
a2:b2
__PLACEHOLDER1_
a4:b6
step3: output:
a1:b1
a2:b2
[a3:b3-c3, b4, b5]
a4:b6
Effectively what you do here is a hierarchical split and replace, since no regex can match context-sensitive (as no regex can count parantheses).
Upvotes: 1
Reputation: 627468
You can use this regex ,(?![^\[]*\])
:
String str="a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6";
System.out.println(Arrays.toString(str.split(",(?![^\\[]*\\])")));
It will ignore all commas inside the square brackets.
import java.util.Arrays;
public class HelloWorld{
public static void main(String []args){
String str="a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6";
System.out.println(Arrays.toString(str.split(",(?![^\\[]*\\])")));
}
}
Output:
[a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6]
Upvotes: 0