2014-09-04 17 views
1

我正在尋找一個匹配以下的正則表達式模式,但我有點難住到目前爲止。我不確定如何抓住我想要的兩組結果,標記爲idattr自定義函數的Java正則表達式

應符合:

  • account[id].attr
  • account[anotherid].anotherattr

這些應該分別返回id, attr
anotherid, anotherattr

任何提示嗎?

+0

我們可以看到你試圖解決這個任務嗎?你如何看待可以匹配'account [xxx] .yyy'的正則表達式? – Pshemo 2014-09-04 15:59:48

+1

這似乎不清楚。請多解釋一下。 – 2014-09-04 15:59:59

+0

我想我只想匹配account [sometext] .moretext並獲取sometext和moretext字段。這似乎是可能的! – phouse512 2014-09-04 16:18:09

回答

2

下面是一個完整的解決方案映射您id - >attribute S:

String[] input = { 
     "account[id].attr", 
     "account[anotherid].anotherattr" 
}; 
//       | literal for "account" 
//       |  | escaped "[" 
//       |  | | group 1: any character 
//       |  | | | escaped "]" 
//       |  | | | | escaped "." 
//       |  | | | | | group 2: any character 
Pattern p = Pattern.compile("account\\[(.+)\\]\\.(.+)"); 
Map<String, String> output = new LinkedHashMap<String, String>(); 
// iterating over input Strings 
for (String s: input) { 
    // matching 
    Matcher m = p.matcher(s); 
    // finding only once per input String. Change to a while-loop if multiple instances 
    // within single input 
    if (m.find()) { 
     // back-referencing group 1 and 2 as key -> value 
     output.put(m.group(1), m.group(2)); 
    } 
} 
System.out.println(output); 

輸出

{id=attr, anotherid=anotherattr} 

注意

在此實現, 「不完整」 的投入,如"account[anotherid]."不會被放入Map,因爲它們根本不匹配Pattern

爲了擁有這些案件把儘可能id - >null,你只需要在Pattern的末尾添加?

這將使最後一組可選。

+0

hmm http://snag.gy/ZHHzk.jpg顯示它不匹配...否則看起來不錯! – phouse512 2014-09-04 16:52:08

+0

@ phouse512查詢服務器,「404」。儘管使用Java測試Java'Pattern'具有比Web工具明顯的優勢,實際上它看起來與Java正則表達式引擎相匹配。 – Mena 2014-09-04 17:17:57

+0

哎呀這是它:http://snag.gy/CCb2l.jpg – phouse512 2014-09-04 17:19:39