gpt4 book ai didi

java - 将字符串(使用正则表达式)转换为可用对象

转载 作者:行者123 更新时间:2023-11-30 02:35:20 27 4
gpt4 key购买 nike

对于一个项目,我们正在使用 telnet 服务器,我们从中接收数据。从 telnet 连接读取一行后,我得到以下字符串:

原始字符串:

SVR GAME MOVE {PLAYER: "PLAYER", MOVE: "1", DETAILS: ""}

我正在尝试将其转换为我可以轻松使用的输出,而不会发生太多可利用性。所需的格式是轻松获取(玩家)或获取。我尝试将 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();
}

问题是,当详细信息为空时,这会导致意外的标记右括号(})。此外,当玩家使用剥削性名称(例如名称中的引号)时,代码很容易崩溃。

将原始字符串转换为可以轻松获得单独设置(玩家、移动、详细信息)的输出的最佳方法是什么?

最佳答案

这将解析字符串并将变量放入映射中:

    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));
}

关于java - 将字符串(使用正则表达式)转换为可用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com