Java 使用模式和匹配器从字符串中获取特定值

Java 使用模式和匹配器从字符串中获取特定值,java,design-patterns,pattern-matching,Java,Design Patterns,Pattern Matching,我想使用返回给我的模式(ssid,psk,优先级)作为键 以及与每个键关联的值。 如果有办法理解我必须使用的表达方式 像 回答我 这是我的绳子 network={ ssid="name" psk="password" key_mgmt=WPA-PSK priority=1 } network={ ssid="another name" psk="another password" key_mgmt=WPA-PSK

我想使用返回给我的模式(ssidpsk优先级)作为键 以及与每个键关联的值。 如果有办法理解我必须使用的表达方式 像

回答我

这是我的绳子

network={
     ssid="name"
     psk="password"
     key_mgmt=WPA-PSK
     priority=1
}

network={
     ssid="another name"
     psk="another password"
     key_mgmt=WPA-PSK
     priority=1
}

以下是一个丑陋的解决方案:

我将您的文本输入放入名为
file.txt
的文件中,并通过BufferedReader读取它

public static void main(String[] args) throws Exception {
        File f = new File("src/test/file.txt");
        BufferedReader read = new BufferedReader(new FileReader(f));
        String temp;
        String result = "";
        while ((temp = read.readLine()) != null) {
            result += temp;
        }
        result = result.replaceAll("\\{", " ");
        result = result.replaceAll("\\}", " ");
        result = result.replaceAll("network=", " ");
        result = result.trim();

        String[] list = result.split("[ ]+(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        for (String s : list) {
            s = s.trim();
            Pattern p = Pattern.compile("(.*)=(.*)");
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println("Key: " + m.group(1));
                System.out.println("Value: " + m.group(2));
            }
        }

    }
这是我的输出:

Key: ssid
Value: "name"
Key: psk
Value: "password"
Key: key_mgmt
Value: WPA-PSK
Key: priority
Value: 1
Key: ssid
Value: "another name"
Key: psk
Value: "another password"
Key: key_mgmt
Value: WPA-PSK
Key: priority
Value: 1

你是用换行符格式化的还是那样的?就是这样。。wpa_恳求者。非常感谢。。这对我来说很有用,但如果他们的方法更好,请写下来。
Key: ssid
Value: "name"
Key: psk
Value: "password"
Key: key_mgmt
Value: WPA-PSK
Key: priority
Value: 1
Key: ssid
Value: "another name"
Key: psk
Value: "another password"
Key: key_mgmt
Value: WPA-PSK
Key: priority
Value: 1