我有以下字符串:
“有龙纹身的女孩(LISBETH)”
我需要在输入的末尾只显示括号中的字符串。
到目前为止,我来到这里:
public static void main(String[] args) {
Pattern pattern =
Pattern.compile("\\({1}([a-zA-Z0-9]*)\\){1}");
Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text " + matcher.group()
+ " starting at " + "index " + matcher.start()
+ " and ending at index " +
matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found");
}
}
但结果我得到:(LISBETH)
。
如何摆脱这些括号?
谢谢!
答案 0 :(得分:10)
使用此模式:\\((.+?)\\)
然后获取组1
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\((.+?)\\)");
Matcher matcher = pattern.matcher("The girl with the dragon tattoo (LISBETH)");
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text " + matcher.group(1)
+ " starting at " + "index " + matcher.start()
+ " and ending at index " +
matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found");
}
}
答案 1 :(得分:3)
您非常接近,只需将group()
,start()
和end()
来电更改为group(1)
,start(1)
和end(1)
,因为您已经拥有它在“匹配组”中。
引自api:
public String group()
返回上一个匹配项匹配的输入子序列。
和
public String group(int group)
返回上一个匹配操作期间给定组捕获的输入子序列。
答案 2 :(得分:3)
使用后视并向前看,然后您不需要使用/访问组
Pattern.compile("(?<=\\()[a-zA-Z0-9]*(?=\\))");
那些背后/前方的外观不匹配,它们只是“检查”,所以这些括号不会成为比赛的一部分。