Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex to get Data between curly brackets

Tags:

java

regex

I am looking for a regular expression to match the text between curly brackets.

{one}{two}{three}

I want each of these as separate groups, as one two three separately.

I tried Pattern.compile("\\{.*?\\}"); which removes only first and last curly brackets.

like image 388
Nishikant Avatar asked Feb 14 '26 23:02

Nishikant


1 Answers

You need to use a capturing group ( ) around what you want to capture.

To just match and capture what is between your curly brackets.

String s  = "{one}{two}{three}";
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group(1));
}

Output

one
two
three

If you want three specific match groups...

String s  = "{one}{two}{three}";
Pattern p = Pattern.compile("\\{([^}]*)\\}\\{([^}]*)\\}\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group(1) + ", " + m.group(2) + ", " + m.group(3));
}

Output

one, two, three
like image 147
hwnd Avatar answered Feb 16 '26 12:02

hwnd