Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String in java by specified pattern

How to split this String in java such that I'll get the text occurring between the braces in a String array?

GivenString = "(1,2,3,4,@) (a,s,3,4,5) (22,324,#$%) (123,3def,f34rf,4fe) (32)"

String [] array = GivenString.split("");

Output must be:

array[0] = "1,2,3,4,@"
array[1] = "a,s,3,4,5"
array[2] = "22,324,#$%"
array[3] = "123,3def,f34rf,4fe"
array[4] = "32" 
like image 861
mayank bansal Avatar asked May 13 '16 13:05

mayank bansal


2 Answers

You can try to use:

Matcher mtc = Pattern.compile("\\((.*?)\\)").matcher(yourString);
like image 160
Rahul Tripathi Avatar answered Sep 21 '22 16:09

Rahul Tripathi


The best solution is the answer by Rahul Tripathi, but your question said "How to split", so if you must use split() (e.g. this is an assignment), then this regex will do:

^\s*\(|\)\s*\(|\)\s*$

It says:

  • Match the open-parenthesis at the beginning
  • Match close-parenthesis followed by open-parenthesis
  • Match the close-parenthesis at the end

All 3 allowing whitespace.

As a Java regex, that would mean:

str.split("^\\s*\\(|\\)\\s*\\(|\\)\\s*$")

See regex101 for demo.

The problem with using split() is that the leading open-parenthesis causes a split before the first value, resulting in an empty value at the beginning:

array[0] = ""
array[1] = "1,2,3,4,@"
array[2] = "a,s,3,4,5"
array[3] = "22,324,#$%"
array[4] = "123,3def,f34rf,4fe"
array[5] = "32"

That is why Rahul's answer is better, because it won't see such an empty value.

like image 39
Andreas Avatar answered Sep 19 '22 16:09

Andreas