我正在尋找一個匹配以下的正則表達式模式,但我有點難住到目前爲止。我不確定如何抓住我想要的兩組結果,標記爲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