我有以下字符串:从正方括号中取出字符串的正则表达式?
“龙纹身(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)
。
如何摆脱这些括号?
谢谢!
+1,但不是正面看起来后面有等号“(?<= \\()'? – 2012-04-03 09:07:16
@PetarMinchev当然你是对的,更正了。 – stema 2012-04-03 09:08:09
我的一般技巧:*不要使用lookarounds当你不需要的时候*不仅会使表达式不必要地复杂化,而且在某些情况下它也是错误的。在这种情况下它可以正常工作,但是例如,如果你想查找带引号的子字符串,例如'(? <=“)[^”] *(?=“)'你会得到无效的结果,在''foo”bar“baz”中会找到'foo','bar'和'baz'。 – Qtax 2012-04-03 09:22:50