Reputation: 572
I have this strings like this one as input:
(1,3,4,(3,4,21),55,69,12,(3,8),9)
and I would like to have this output, as an array or a list of strings
1 - 3 - 4 - (3,4,21) - 55 - 69 - 12 - (3,8) - 9
Could someone help? I've tried a couple regex but had no luck.
EDIT: Please note that the "-" in the output represents a different element of the same array or list, not a desidered character.
Example: array[0]="1"; array[1]="3"; array[3]="(3,4,21)";
Upvotes: 0
Views: 95
Reputation: 10466
You may try this regex:
,(?!(?:(?:[^\(\)]*[\(\)]){2})*[^\(\)]*$)
This will match all the commas(,) that should be replaced by - or you may split by the above regex as well
Explanation:
The logic is to find a comma that is not followed by even numbers of brackets ( and )
Sample Source ( run here ):
final String regex = ",(?!(?:(?:[^\\(\\)]*[\\(\\)]){2})*[^\\(\\)]*$)";
final String string = "(1,3,4,(3,4,21),55,69,12,(3,8),9)";
String[] result=string.split(regex);
int len=result.length;
for(int i=0;i<len;i++)
{
// the following two if condition is necessary to remove the start and end brace
// many other and probably better alternatives could be there to remove it
if(result[i].contains("(") && !result[i].contains(")"))
result[i]=result[i].replace("(","");
else if(result[i].contains(")") && !result[i].contains("("))
result[i]=result[i].replace(")","");
}
System.out.println(java.util.Arrays.toString(result));
Output:
[1, 3, 4, (3,4,21), 55, 69, 12, (3,8), 9]
Upvotes: 3