2014-09-04 66 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