Java String parsing – {k1=v1,k2=v2,…}


I have the following string which will probably contain ~100 entries:

String foo = "{k1=v1,k2=v2,...}"

and am looking to write the following function:

String getValue(String key){
    // return the value associated with this key

I would like to do this without using any parsing library. Any ideas for something speedy?

Best Solution

If you know your string will always look like this, try something like:

HashMap map = new HashMap();

public void parse(String foo) {
  String foo2 = foo.substring(1, foo.length() - 1);  // hack off braces
  StringTokenizer st = new StringTokenizer(foo2, ",");
  while (st.hasMoreTokens()) {
    String thisToken = st.nextToken();
    StringTokenizer st2 = new StringTokenizer(thisToken, "=");

    map.put(st2.nextToken(), st2.nextToken());

String getValue(String key) {
  return map.get(key).toString();

Warning: I didn't actually try this; there might be minor syntax errors but the logic should be sound. Note that I also did exactly zero error checking, so you might want to make what I did more robust.