簡體   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