我正在寻找一个匹配以下的正则表达式模式,但我有点难住到目前为止。我不确定如何抓住我想要的两组结果,标记为id
和attr
。自定义函数的Java正则表达式
应符合:
account[id].attr
account[anotherid].anotherattr
这些应该分别返回id, attr
,
和anotherid, anotherattr
任何提示吗?
我正在寻找一个匹配以下的正则表达式模式,但我有点难住到目前为止。我不确定如何抓住我想要的两组结果,标记为id
和attr
。自定义函数的Java正则表达式
应符合:
account[id].attr
account[anotherid].anotherattr
这些应该分别返回id, attr
,
和anotherid, anotherattr
任何提示吗?
下面是一个完整的解决方案映射您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
的末尾添加?
。
这将使最后一组可选。
我们可以看到你试图解决这个任务吗?你如何看待可以匹配'account [xxx] .yyy'的正则表达式? – Pshemo 2014-09-04 15:59:48
这似乎不清楚。请多解释一下。 – 2014-09-04 15:59:59
我想我只想匹配account [sometext] .moretext并获取sometext和moretext字段。这似乎是可能的! – phouse512 2014-09-04 16:18:09