【问题标题】:How to find element in brackets [duplicate]如何在括号中查找元素[重复]
【发布时间】:2020-10-22 10:53:31
【问题描述】:

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

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

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

结果:

@Test(value123)

但我需要

值123

【问题讨论】:

  • 显示您的代码。
  • 你需要使用look behind/ahead or groups

标签: java regex


【解决方案1】:

添加(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
}

输出

value123

解释

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

或者,使用 (?<=X) zero-width positive lookbehind(?=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
}

输出

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

【讨论】:

  • 谢谢你,它的工作。祝你好运!
【解决方案2】:

您可以使用匹配器,如下所示:

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
    }
  }
}

【讨论】:

  • 谢谢你,它的工作。祝你好运!
  • @MaximMaxim 如果你觉得这两个答案有用,你应该投票赞成。
  • @Andreas 我只能为一个答案投票。如何为两个答案投票?
  • @MaximMaxim 按向上的箭头,而不是对勾。
  • @Andreas “感谢您的反馈!声望低于 15 人的投票将被记录,但不要更改公开显示的帖子得分。”
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 2020-08-21
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 2016-12-29
  • 2014-01-08
  • 1970-01-01
相关资源
最近更新 更多