How to search a string of key/value pairs in Java

社会主义新天地 提交于 2019-12-04 06:39:00

Use String.split:

String[] kvPairs = "key1=value1;key2=value2;key3=value3".split(";");

This will give you an array kvPairs that contains these elements:

key1=value1
key2=value2
key3=value3

Iterate over these and split them, too:

for(String kvPair: kvPairs) {
   String[] kv = kvPair.split("=");
   String key = kv[0];
   String value = kv[1];

   // Now do with key whatever you want with key and value...
   if(key.equals("specialkey")) {
       // Do something with value if the key is "specialvalue"...
   }
}

I would parse the String into a map and then just check for the key:

String rawValues = "key1=value1;key2=value2;key3=value3";
Map<String,String> map = new HashMap<String,String>();
String[] entries = rawValues.split(";");
for (String entry : entries) {
  String[] keyValue = entry.split("=");
  map.put(keyValue[0],keyValue[1]);
}

if (map.containsKey("myKey") {
   return map.get("myKey");
}

If it's just the one key you're after, you could use regex \bspecialkey=([^;]+)(;|$) and extract capturing group 1:

Pattern p = Pattern.compile("\\bspecialkey=([^;]+)(;|$)");
Matcher m = p.matcher("key1=value1;key2=value2;key3=value3");

if (m.find()) {
    System.out.println(m.group(1));
}

If you're doing something with the other keys, then split on ; and then = within a loop - no need for regex.

Just in case anyone is interested in a pure Regex-based approach, the following snippet works.

Pattern pattern = Pattern.compile("([\\w]+)?=([\\w]+)?;?");
Matcher matcher = pattern.matcher("key1=value1;key2=value2;key3=value3");
while (matcher.find()) {
   System.out.println("Key - " + matcher.group(1) + " Value - " + matcher.group(2);
}

Output will be

Key - key1 Value - value1
Key - key2 Value - value2
Key - key3 Value - value3

However, as others explained before, String.split() is recommended any day for this sort of task. You shouldn't complicate your life trying to use Regex when there's an alternative to use.

Regex is well suited to matching and parsing at the same time:

//c#
string input = @"key1=value1;specialkey=scott;key3=value3";
var specialkey = Regex.Match(input, "specialkey=(.*?);").Groups[1].Value;
Console.WriteLine(specialkey);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!