2014-11-25 21 views
-1

我有以下文字來自我需要檢索特定信息(可能是多行):正則表達式來獲取重複組

Type [Hello] Server [serverName]. [BC]. [CD] [D" + 
       "E]. [FH]. [MN]. [CS]., ID = 53ec9d" 

從文本我需要檢索:

serverName和以下條目在[]之間,由" ."分隔。他們可以重複任何次數。他們的結局是".,".

表示因此,在上述情況下我的輸出應該是:

serverName : serverName

和值應爲:

BC , CD, DE,FH, MN,CS 

需要幫助的要求。

+1

你忘了'[']''後'[CD]'? – 2014-11-25 10:43:47

+1

你的方法是什麼?與我們分享你的嘗試,這樣你可以得到更好的幫助。 – Maroun 2014-11-25 10:43:49

+1

什麼是[D「+」E] – 2014-11-25 10:45:06

回答

0

對於這種觀點:

public static void main(String[] args) { 
    String s = "Type [Hello] Server [serverName]. [BC]. [CD] [DE]. [FH]. [MN]. [CS]., ID = 53ec9d"; 

    /* 
    * anything that is surrounded by [ ] characters and doesn't contain [ ] 
    */ 
    Pattern compile = Pattern.compile("\\[([^\\[\\]]+)\\]"); 
    Matcher matcher = compile.matcher(s); 

    boolean first = true, second = true; 
    while (matcher.find()) { 

     if (first) { // avoiding [Hello] 
      first = false; 
      continue; 
     } 

     // remove surrounding [ ] 
     String currentValue = matcher.group(1).replaceAll("\\[|\\]", ""); 

     // first find is treated differently 
     if (second) { 
      second = false; 
      System.out.println("serverName = " + currentValue); 
      continue; 
     } 

     System.out.println(currentValue); 
    } 
} 

輸出爲:

serverName = serverName 
BC 
CD 
DE 
FH 
MN 
CS