Oppure, con una regex per la creazione di token, e una macchina a stati poco che aggiunge solo la chiave/val a una mappa:
String line = "a = b c='123 456' d=777 e = 'uij yyy'";
Map<String,String> keyval = new HashMap<String,String>();
String state = "key";
Matcher m = Pattern.compile("(=|'[^']*?'|[^\\s=]+)").matcher(line);
String key = null;
while (m.find()) {
String found = m.group();
if (state.equals("key")) {
if (found.equals("=") || found.startsWith("'"))
{ System.err.println ("ERROR"); }
else { key = found; state = "equals"; }
} else if (state.equals("equals")) {
if (! found.equals("=")) { System.err.println ("ERROR"); }
else { state = "value"; }
} else if (state.equals("value")) {
if (key == null) { System.err.println ("ERROR"); }
else {
if (found.startsWith("'"))
found = found.substring(1,found.length()-1);
keyval.put (key, found);
key = null;
state = "key";
}
}
}
if (! state.equals("key")) { System.err.println ("ERROR"); }
System.out.println ("map: " + keyval);
stampe fuori
map: {d=777, e=uij yyy, c=123 456, a=b}
Fa un controllo di base dell'errore e prende le virgolette dai valori.
Non potresti usare una regex per dividere per spazi a meno che tu non sia all'interno di una citazione (non che io sappia regex, ma sono abbastanza sicuro che puoi farlo). – mk12
Il tuo codice funziona perfettamente qui usando jdk 1.6.0_13 –
@LePad sopra il codice verrà emesso * [a = b, c = '123, 456', d = 777, e = 'uij, yyy'] * –