/* * MapStringParser.java * * Copyright (C) 2003 Miika Nurminen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import java.util.StringTokenizer; import java.util.Map; import java.util.HashMap; /** * Parses strings of type key1=value1;key2=value2;... to a map. * Can be used for example to parse a CSS-styled declaration. * * @version 0.1 - 2003-8-7 * @author minurmin */ public class MapStringParser { String itemSeparator; String pairSeparator; public MapStringParser() { this.itemSeparator = "="; this.pairSeparator = ";"; } public MapStringParser(String itemSeparator,String pairSeparator) { this.itemSeparator = itemSeparator; this.pairSeparator = pairSeparator; } public Map parse(String s) { Map result = new HashMap(); if (s==null) return result; StringTokenizer t = new StringTokenizer(s,pairSeparator); while (t.hasMoreTokens()) { StringTokenizer inner = new StringTokenizer(t.nextToken(),itemSeparator,true); if (inner.hasMoreTokens()) { String key = inner.nextToken(); String value = ""; if (key.equals(itemSeparator)) { key = ""; } else inner.nextToken(); // this should be a separator. if (inner.hasMoreTokens()) value = inner.nextToken(); result.put(key,value); } else result.put("",""); } return result; } // UNIT TEST ----------------------------------------------------------------- private static void test(String s) { MapStringParser p = new MapStringParser(); Map m = p.parse(s); System.out.println(m.toString()); } /** * Unit test. Working. * @param args the command line arguments */ public static void main(String[] args) { test("testi=val1;toinen=val2"); test(""); test("noval=;=nokey"); test(null); test("another=21323;="); } }