有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想使用返回给我的模式(ssidpskproority)作为 以及与每个相关的。 如果有办法理解我必须使用的表达方式 就像

Pattern.compile("(\\w+?):(\\w+?),")

回复我

这是我的绳子

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

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

共 (1) 个答案

  1. # 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