2012-04-03 125 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組)

返回以前的匹配操作期間由給定組捕獲的輸入子序列。

相關問題