2

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.

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

0

If you want 3 groups, your pattern needs 3 groups.

"\\{([^}]*)\\}\\{([^}]*)\\}\\{([^}]*)\\}"
              ^^^^^^^^^^^^^

(The middle part is the same as the left and right).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.