Java parsing and extract String from pattern String I want to extract some string surrounded by certain patterns.

For Instance, the original String something like 1234@{78}dasdh@{1}fdsfs@{fdf}ad@{
and I want extract 78, 1, fdf from it.

Below is my code for the purpose

public class Test {

    // want to get "78", "1", "fdf"
    private static String targetStr = "1234@{78}dasdh@{1}fdsfs@{fdf}ad@{";

    public static void main (String[] args) throws Exception {

        List&lt;String&gt; parsed = new ArrayList&lt;&gt;();

        Pattern open = Pattern.compile("@\\{");
        Matcher oMatcher = open.matcher(targetStr);

        Pattern close = Pattern.compile("}");
        Matcher cMatcher = close.matcher(targetStr);

        while(oMatcher.find()) {
            if(cMatcher.find())  parsed.add(targetStr.substring(oMatcher.start() + 2, cMatcher.start()));
        }
        System.out.println(parsed);
    }
}


Is there anyway to complete this task? Some how it feels unsafe since use 2 iterator without any validation.
There's a simpler way:

Pattern p = Pattern.compile("\\w+@\\{(\\w+)\\}");
Matcher m = p.matcher(targetStr);
while (m.find()) {
    parsed.add(m.group(1));
}


Instead of matching the opening and closing braces separately, the above pattern matches a whole expression of the form aaa@{bbb} at once. And when it finds the expression, it remembers the part inside the braces. This is done via a capturing group (the parentheses).

To learn more about each of the characters in the pattern, read the Javadoc of the Pattern class.