-3

I need the value in parentheses for the annotation in the text field. Example:

String text = "I have simple annotation @Test(value123) and ..

I can find the annotation itself with a value, but I don't understand how to get it without an annotation Pattern patternString = Pattern.compile("@Test\\(\\s+\\)");

Result:

@Test(value123)

but I need

value123

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Raketa
  • 11
  • 5

2 Answers2

2

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
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

You can use a matcher, like this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Main {
  public static void main(String[] args) {
    String testString = "@Test(value123)";
    // unescaped parentheses catch the group
    // note that I changed \\s+ to .+,
    // since I want to match whatever is inside the parentheses,
    // not whitespaces (however, you should adjust it to your needs)
    Pattern pattern = Pattern.compile("@Test\\((.+)\\)");
    Matcher matcher = pattern.matcher(testString);
    if (matcher.matches()) {
      String value = matcher.group(1);
      System.out.println(value); // prints value123
    }
  }
}