java - 如何在括号中查找元素
问题描述
我需要括号中的值作为文本字段中的注释。例子:
String text = "I have simple annotation @Test(value123) and ..
我可以找到带有值的注释本身,但我不明白如何在没有注释的情况下获取它
Pattern patternString = Pattern.compile("@Test\\(\\s+\\)");
结果:
@Test(值123)
但是我需要
价值123
解决方案
添加(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
推荐阅读
- android - 使用模型类时在firebase中添加数据时设置自定义键
- c - 为什么 math.h 中的 cos 函数比 x86 fcos 指令快
- mysql - 如何优化此内连接查询以减少查询时间
- java - 从进度对话框中删除背景
- html - 背景图像中的文本溢出
- angular - 带有 Google Cloud App Engine 的 Angular html5 模式
- java - Java 方法调用监听器
- java - 在 Eclipse 项目中使用 MapStruct 将“脏”字符串字段映射为双精度
- laravel - 如何获取数据透视数据取决于模型绑定
- javascript - 如何解决问题当前未启用对实验语法“classProperties”的支持