我从给定的游戏服务器收到以下命令:
SVR GAME MOVE {
PLAYER: "player2",
MOVE: "26",
DETAILS: ""
}
现在我想用正则表达式获取move的值。 *注意播放器名称是一个变量登录名,因此它也可以包含很多数字。
我尝试了以下内容:
Pattern pat = Pattern.compile(".*MOVE: *([0-9]+).*");
Matcher mat = pat.matcher(parse);
if(mat.matches()) {
parse = mat.group(1);
}
* parse包含带命令的字符串。
有人可以解释一下我做错了吗?
提前致谢
答案 0 :(得分:1)
尝试这种方法:
String str = "SVR GAME MOVE {PLAYER: \"player2\", MOVE: \"26\", DETAILS: \"\"}";
System.out.println(str.split(",")[1].toString().replaceAll("[^0-9]", ""));
答案 1 :(得分:1)
正则表达式是对的。
Pattern pat = Pattern.compile("MOVE:\s\"([0-9]+)\"");
通过它,您将能够提取数据。此外,您需要使用mat.find()
而不是mat.matches()
:matches
仅在数据与正则表达式匹配时才会返回内容,从头到尾。 find
将扫描数据以查找对应的子序列;检查此信息以获取更多信息https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html
答案 2 :(得分:1)
你错过了正则表达式中的"
:
public static void main(String[] args) {
String line = "SVR GAME MOVE {PLAYER: \"player2\", MOVE: \"26\",DETAILS: \"\"}";
Pattern pat = Pattern.compile(".*MOVE: *\"([0-9]+).*");
Matcher mat = pat.matcher(line);
if(mat.matches()) {
String move = mat.group(1);
System.out.println(move);
}
}
打印 26