Add a (X)
capturing group:
String text = "I have simple annotation @Test(value123) and ..";
Pattern p = Pattern.compile("@Test\\(([^)]*)\\)");
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println(m.group(1)); // Print capture group 1
}
Output
value123
Explanation
@Test\( Match '@Test('
( Start of capturing group 1
[^)]* Match zero-or-more characters, except ')'
) End of capturing group 1
\) Match ')'
Alternatively, use (?<=X)
zero-width positive lookbehind and (?=X)
zero-width positive lookahead:
String text = "I have simple annotation @Test(value123) and ..";
Pattern p = Pattern.compile("(?<=@Test\\()[^)]*(?=\\))");
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println(m.group()); // Print matched text
}
Output
value123
Explanation
(?<= Start of zero-width positive lookbehind
@Test\( Match '@Test('
) End of zero-width positive lookbehind
[^)]* Match zero-or-more characters, except ')'
(?= Start of zero-width positive lookahead
\) Match ')'
) End of zero-width positive lookahead