简体   繁体   中英

Processing the particular key value pair in set of key value pairs in java

The string can be "accountno=18&username=abc&password=1236" or "username=abc&accountno=18&password=1236" or the accountno can be present anywhere in the string. I need to get the accountno details from this string using a key value pair. I used spilt on "&" but I'm unable to get the result.

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);

    }
}

How can I get the accountno value from this above string as key value pair in java

You may handle this by first splitting on & to isolate each key/value pair, then iterate that collection and populate a 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"));

This prints:

account number is: 18

Using some simple tools, like string.split and Map, you can easly do that:

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;
}

To get a specific value, like "accountno", just retrive that key map.get("accountno")

As you said

the accountno can be present anywhere in the string

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));
}

This would work even when accountno is somewhere in the middle of the string

Output:

Account no 18

You can try out regex here:

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

The same answer mentioned by @vinicius can be achieved using Java 8 by:

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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