简体   繁体   English

拆分正则表达式的结果

[英]splitting the results of a regular expression

With the following code I was able to get all the necessary information out of a form, this information is; 通过以下代码,我能够从表格中获取所有必要的信息,这些信息是:

n = 5
p = 0.5
lambda = 0.3
d = 1
n = 8
p = 0.1
d = 1
p = 0.3

I put all this information in a HashMap, but what I actually need would be 6 hashmaps; 我把所有这些信息都放在了一个HashMap中,但实际上我需要的是6个hashmap。 like this 像这样

Hashmap 1
n = 5
p = 0.5
Hashmap 2
lambda = 0.3
Hashmap 3
d = 1
Hashmap 4
n = 8
p = 0.1
Hashmap 5
d = 1
Hashmap 6
p = 0.3

In other words, always when I get an n as keyword, the next keyword and value should also be stored in this Hashmap, this next keyword will always be an p. 换句话说,总是当我得到n作为关键字时,下一个关键字和值也应该存储在此Hashmap中,该下一个关键字将始终是p。

I know it is not really possible to split a Hashmap, but I can't find any other way 我知道实际上不可能拆分Hashmap,但是我找不到其他方法

Thanks a lot 非常感谢

public static void main(String[] args ) throws FileNotFoundException, IOException        
{
     File filename = new File("H:\\NetBeansProjects\\thesis2.0\\src\\thesis2\\pkg0\\txt-files\\formulier.txt");

     try (BufferedReader in = new BufferedReader(new FileReader(filename))) 
     {

        HashMap hm = new HashMap();

        Pattern p = Pattern.compile("\\s+(\\w+)\\s+([0-9.]+)\\s*");
        for (String line; (line = in.readLine()) != null; ) 
        {
            Matcher m = p.matcher(line);
            if (m.matches()) 
            {
                String keyword = m.group(1);
                String parameter = m.group(2);

                hm.put(m.group(1),m.group(2));

                System.out.println(m.group(1) + " = " + m.group(2));
            }
       }
    }  
}

You can use a List<> to store the Map<> s, you basicly need to create a simple token based parser for the values that dispatches it to the next Map . 您可以使用List<>来存储Map<> ,基本上,您需要为该值创建一个简单的基于令牌的解析器,以将其分派到下一个Map

List<Map<String,String>> motherList = new ArrayList<>();
Map<String,String> workingChild = new HashMap<>();

.... 

String keyword = m.group(1);
String parameter = m.group(2);

workingChild.put(keyword,parameter);
if(!keyword.equals("n")) {
    motherList.add(workingChild);
    workingChild = new HashMap<>();
}

We basically have 1 motherlist containing al our child maps, for every input keyword and parameter, we put it in our current work map, and then we put it in the motherMap ONLY if the last token wasn't "n". 我们基本上有1个母列表,其中包含所有子映射,对于每个输入关键字和参数,我们将其放入当前工作映射中,然后仅在最后一个标记不是“ n” motherMap将其放入motherMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM