Split string in java by given pattern

How to split this string in java so that I get text between curly 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("");

The output should 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" 
+4
source share
3 answers

You can try:

Matcher mtc = Pattern.compile("\\((.*?)\\)").matcher(yourString);
+7
source

The best solution is Rahul Tripathi's answer , but your question said: “How split, ” so if you have to use split()(for example, this assignment), then this regular expression will do:

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

It says:

  • Match the open parenthesis at the beginning
  • Match the close bracket to the open bracket

3 .

Java :

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

regex101 .

split() , , :

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"

, .

+1

split(), , char.

, . - , '('. ,

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

, char ')', , . ( "," "), ( " " ).

, :

String a = "(1,2,3,4,@) (a,s,3,4,5) (22,324,#$%) (123,3def,f34rf,4fe) (32)" 
a = a.replace("(","");
//a is now equal to 1,2,3,4,@) a,s,3,4,5) 22,324,#$%) 123,3def,f34rf,4fe) 32)
String[] parts = a.split("\\)");

System.out.println(parts[0]); //this will print 1,2,3,4,@

, !

[], !

0

All Articles