对于一个项目,我们正在使用Telnet服务器,从中接收数据。
从telnet连接读取一行后,我得到以下字符串:
原始字串:
SVR GAME MOVE {PLAYER: "PLAYER", MOVE: "1", DETAILS: ""}
我正在尝试将其转换为可以轻松使用的输出,而不会发生太多可利用性。
所需的格式是轻松获取(PLAYER)或获取。我尝试将regex与json结合使用,请参见以下代码:
String line = currentLine;
line = line.replaceAll("(SVR GAME MOVE )", ""); //remove SVR GAME MATCH
line = line.replaceAll("(\"|-|\\s)", "");//remove quotations and - and spaces (=\s)
line = line.replaceAll("(\\w+)", "\"$1\""); //add quotations to every word
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(line);
//@todo bug when details is empty causes
//@todo example string: SVR GAME MOVE {PLAYER: "b", MOVE: "1", DETAILS: ""}
//@todo string that (line) that causes an error when parsing to json {"PLAYER":"b","MOVE":"1","DETAILS":}
//@todo Unexpected token RIGHT BRACE(}), i think because "details" has no value
System.out.println(json.get("PLAYER"));
System.out.println(json.get("MOVE"));
System.out.println(json.get("DETAILS"));
int index = Integer.valueOf(json.get("MOVE").toString());
for(GameView v : views){
v.serverMove(index);//dummy data is index 1
}
} catch (ParseException e) {
e.printStackTrace();
}
问题是,当详细信息为空时,这将导致出现意外的令牌RIGHT BRACE(})。此外,当玩家使用具有破坏性的名称作为其名称中的引号时,代码将很容易崩溃。
将原始String转换为可轻松获得单独设置(玩家,移动,详细信息)的输出的最佳方法是什么?
最佳答案
这将解析字符串并将变量放入映射中:
Map<String,String> vars = new HashMap<>();
String input = "SVR GAME MOVE {PLAYER: \"PLAYER\", MOVE: \"1\", DETAILS: \"\"}";
Pattern pattern = Pattern.compile("([A-Za-z]+): \"([^\"]*)\"");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
vars.put(matcher.group(1), matcher.group(2));
}