Hoặc, với một regex cho tokenizing, và một máy nhà nước nhỏ mà chỉ bổ sung thêm phím/val vào bản đồ:
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);
in ra
map: {d=777, e=uij yyy, c=123 456, a=b}
Nó thực hiện một số kiểm tra lỗi cơ bản, và trích dẫn các giá trị.
Bạn không thể sử dụng regex để chia nhỏ khoảng trắng trừ khi bạn đang ở trong một báo giá (không phải là tôi biết regex, nhưng tôi khá chắc chắn bạn có thể làm điều đó). – mk12
Mã của bạn hoàn toàn hoạt động ở đây bằng cách sử dụng jdk 1.6.0_13 –
@LePad mã trên sẽ xuất ra * [a = b, c = '123, 456', d = 777, e = 'uij, yyy'] * –