Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string based on a pattern using regex

Tags:

java

regex

I have trouble splitting string based on regex.

String str = "1=(1-2,3-4),2=2,3=3,4=4";
Pattern commaPattern = Pattern.compile("\\([0-9-]+,[0-9-]+\\)|(,)") ;
String[] arr = commaPattern.split(str);
for (String s : arr)
{
    System.out.println(s);
}

Expected output,

1=(1-2,3-4)     
2=2    
3=3    
4=4

Actual output,

1=

2=2
3=3
4=4
like image 352
prasanth Avatar asked Oct 17 '25 20:10

prasanth


1 Answers

This regex would split as required

,(?![^()]*\\))
  ------------
      |->split with , only if it is not within ()
like image 52
Anirudha Avatar answered Oct 19 '25 08:10

Anirudha