2012-04-03 100 views
3

我有以下字符串:从正方括号中取出字符串的正则表达式?

“龙纹身(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)

如何摆脱这些括号?

谢谢!

回答

3

使用向后看和向前看,那么你就需要使用/访问组

Pattern.compile("(?<=\\()[a-zA-Z0-9]*(?=\\))"); 

那些向后看/未来的不匹配,他们只是“检查”,所以那些括号不会成为比赛的一部分。

+0

+1,但不是正面看起来后面有等号“(?<= \\()'? – 2012-04-03 09:07:16

+0

@PetarMinchev当然你是对的,更正了。 – stema 2012-04-03 09:08:09

+2

我的一般技巧:*不要使用lookarounds当你不需要的时候*不仅会使表达式不必要地复杂化,而且在某些情况下它也是错误的。在这种情况下它可以正常工作,但是例如,如果你想查找带引号的子字符串,例如'(? <=“)[^”] *(?=“)'你会得到无效的结果,在''foo”bar“baz”中会找到'foo','bar'和'baz'。 – Qtax 2012-04-03 09:22:50

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"); 
    } 
} 
+0

谢谢,但 - 再次 - 我得到(LISBETH)。因此我只需要LISBETH。 – karla 2012-04-03 09:01:32

+0

你确定吗?编译之前你保存过文件吗?因为我只是将此方法复制到我的项目中,并且它正常工作。 – shift66 2012-04-03 09:02:48

+0

对不起我 - 你的模式奏效了!再次感谢你! – karla 2012-04-03 09:03:25

3

你是非常接近,只是改变group()start()end()调用group(1)start(1)end(1)既然你已经有了它的“匹配组”。

从API引用:

公共字符串组()

返回由以前匹配所匹配的输入子序列。

和:

公共字符串组(INT组)

返回以前的匹配操作期间由给定组捕获的输入子序列。

相关问题