首页 > 解决方案 > 如何在括号中查找元素

问题描述

我需要括号中的值作为文本字段中的注释。例子:

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

我可以找到带有值的注释本身,但我不明白如何在没有注释的情况下获取它 Pattern patternString = Pattern.compile("@Test\\(\\s+\\)");

结果:

@Test(值123)

但是我需要

价值123

标签: javaregex

解决方案


添加(X) 捕获组

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
}

输出

value123

解释

@Test\(     Match '@Test('
(           Start of capturing group 1
  [^)]*       Match zero-or-more characters, except ')'
)           End of capturing group 1
\)          Match ')'

或者,使用(?<=X) 零宽度正向后看(?=X) 零宽度正向前看

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
}

输出

value123

解释

(?<=          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

推荐阅读