我知道有人问过类似的问题,但我无法找到我想要的涉及方括号的特定内容。

输入以下内容:


[NAME]鲍勃
[NUMBER] 12456703
[STREET]一切[UNIT] 32 [SUBURB] Benmore


我希望能够将此数据输入到hasmap中,其中括号中的文本将是键,而括号中的信息将是数据。
我一直在尝试使用子字符串和拆分,但是每行有一组以上的括号时,我遇到了问题?
非常感谢

最佳答案

试试这个:

 HashMap<String, String> map = new HashMap<String, String>();
 Pattern regex = Pattern.compile("(\\[\\w+\\])\\s+(\\w+)");
 Matcher regexMatcher = regex.matcher(subjectString);
 while (regexMatcher.find()) {
     // matched text: regexMatcher.group(i)
     // add group 1 to key and group 2 to value of hash
     map.put(regexMatcher.group(1), regexMatcher.group(2));
 }

10-06 14:40