A.Dumas
A.Dumas

Reputation: 3327

Pattern extract between curly brackets

I am trying to extract text within two curly brackets for example given the following string

s = "Some text \test{a}{b}{c} even more " 

I just want to extract all content in b and c as strings. In addition there might be more curly brackets in b and c. I like to extract this text as well.

I have been looking over some functions in Java. As the follwing

String in = "Item(s): \test{x}{y}{z in {X} }";

Pattern p = Pattern.compile("\\{(.*?)\\}");
Matcher m = p.matcher(in);

while(m.find()) {
    System.out.println(m.group(1));
}

But this gives me all content in curly brackets which is

   a="x"
   b="y" 
   c=" z in {X"

Additional question: if the string has multiple different curly bracktes as the following

s1=" Some text \test{a}{b}{c} even more \foo{d}{e}" 

but I still want only b and c. is this easy to implement? For this specific case we can just take iteration 2 and 3 but in general if there is a longer text with multiple \test{}{}{} it is not as simple.

s2 = " Some text \test{a1}{b1}{c1} even more \foo{d}{e} and more \test{a2}{b2}{c2} more plus mehr mas" 

I then want b1, c1 and b2 and c2 For this case we can use a if condition checking for each "\test" and only taking iteration 2 and 3 but that is quite ugly.

Upvotes: 2

Views: 1976

Answers (2)

Toto
Toto

Reputation: 91518

If you have only one nested level, you could try:

[{]([^{}]+|[^{}]*[{][^{}]*[}][^{}]*)[}]

Upvotes: 0

Aihal
Aihal

Reputation: 31

Try StringUtils.substringsBetween if you are using apache commons lang API.

String[] bet = StringUtils.substringsBetween("Some text \test{a}{b}{c} even more ", "{", "}");
System.out.println(Arrays.asList(bet))

;

Upvotes: 1

Related Questions