繁体   English   中英

处理 java 中键值对集中的特定键值对

[英]Processing the particular key value pair in set of key value pairs in java

字符串可以是 "accountno=18&username=abc&password=1236" 或 "username=abc&accountno=18&password=1236" 或者 accountno 可以出现在字符串中的任何位置。 我需要使用键值对从此字符串中获取帐户详细信息。 我在“&”上使用了溢出,但我无法得到结果。

import java.util.regex.*;
public class RegexStrings {
    public static void main(String[] args) {
        String input = "accountno=18&username=abc&password=1236";
        String exten = null;


        Matcher m = Pattern.compile("^accountno: (.&?)$", Pattern.MULTILINE).matcher(input);
        if (m.find()) {
            exten = m.group(1);
        }

        System.out.println("AccountNo: "+exten);

    }
}

如何从上面的字符串中获取 accountno 值作为 java 中的键值对

您可以通过首先拆分&以隔离每个键/值对来处理此问题,然后迭代该集合并填充 map:

String input = "accountno=18&username=abc&password=1236";
String[] parts = input.split("&");
Map<String, String> map = new HashMap<>();
for (String part : parts) {
    map.put(part.split("=")[0], part.split("=")[1]);
}

System.out.println("account number is: " + map.get("accountno"));

这打印:

account number is: 18

使用一些简单的工具,例如 string.split 和 Map,您可以轻松做到:

Map<String, String> parse(String frase){
    Map<String, String> map = new TreeMap<>();
    String words[] = frase.aplit("\\&");
    for(String word : words){
        String keyValuePair = word.split("\\=");
        String key = keyValuePair[0];
        String value = keyValuePair[1];
        map.put(key, value);
    }
    return map;
}

要获取特定值,例如“accountno”,只需检索该键map.get("accountno")

如你所说

accountno可以出现在字符串中的任何位置

String input = "accountno=18&username=abc&password=1236";
//input = "username=abc&accountno=19&password=1236";
Matcher m = Pattern.compile("&?accountno\\s*=\\s*(\\w+)&?").matcher(input);
if (m.find()) {
    System.out.println("Account no " + m.group(1));
}

即使accountno位于字符串中间的某个位置,这也会起作用

Output:

Account no 18

您可以在这里尝试正则表达式:

https://regex101.com/r/nOHmzc/2

@vinicius 提到的相同答案可以使用 Java 8 通过以下方式实现:

Map<String, String> map = Arrays.stream(input.split("&"))
            .map(str -> str.split("="))
            .collect(Collectors.toMap(s -> s[0],s -> s[1]));

//To retrieve accountno from map
System.out.println(map.get("accountno"));

暂无
暂无

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

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