java 正则表达式从简单的 JSON 对象中提取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37828214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to extract value from a simple JSON Object
提问by user1738539
I'm looking to extract values from this JSON based on key without any JSON libraries. I figure it can be done in regex, just don't know how. All values are integers.
我希望根据没有任何 JSON 库的键从这个 JSON 中提取值。我认为它可以在正则表达式中完成,只是不知道如何。所有值都是整数。
{"key1":11,"key2":2877,"key3":666,"key4":2906}
I want to return for example, the integer 11, if I give key1 as the input to my method.
例如,如果我将 key1 作为我方法的输入,我想返回整数 11。
public String valueFromKey(String key, String json) {
String result = null;
String patternStr= "Some regex with " + key;
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(json);
while (matcher.find())
result = matcher.group(1);
}
return result;
}
// elsewhere..
String numStr = valueFromKey("key1", "{\"key1\":11,\"key2\":2877,\"key3\":666,\"key4\":2906}");
if (numStr != null)
int val = Integer.parseInt(numStr);
回答by T.J. Crowder
I would just use a JSON parser.
我只会使用 JSON 解析器。
Having said that, you've said:
话虽如此,你已经说过:
- You don't want to
- All the values will be integers
- 你不想
- 所有的值都是整数
Ifwe add to that another major assumption:
如果我们再加上另一个主要假设:
- The JSON will be in its minimal form, not formatted (no spaces around the
:
between property names and values)
- JSON 将采用其最小形式,未格式化(
:
属性名称和值之间没有空格)
Then yes, it's possible, with a fairly simple regular expression:
那么是的,这是可能的,使用一个相当简单的正则表达式:
"key1":(\d+)
Since Java doesn't have regex literals, the string for that has some backslashes in it for characters we need to use that are special in string literals (specifically, "
and \
):
由于 Java 没有正则表达式文字,因此该字符串中有一些反斜杠,用于我们需要使用在字符串文字中特殊的字符(特别是"
和\
):
Pattern p = Pattern.compile("\"key1\":(\d+)");
That defines a match for the literal string "key1":
followed by one or more digits, and defines the digits as a capture group. Here's an example in JavaScript:
这定义了"key1":
后跟一个或多个数字的文字字符串的匹配,并将这些数字定义为捕获组。这是 JavaScript 中的示例:
var json = '{"key1":11,"key2":2877,"key3":666,"key4":2906}';
var match = /"key1":(\d+)/.exec(json);
console.log(match ? "Got " + match[1] : "No match");
I don't recommend it, but with those assumptions, it's possible.
我不推荐它,但有了这些假设,这是可能的。
回答by Krzysztof Krasoń
It is best to use Json Parser, but if you insist:
最好使用 Json Parser,但如果你坚持:
Pattern pattern = Pattern.compile(
String.format("\"%s\":\s([0-9]+)", key)
);
Here I assume the values are only digits and there can be a whitespace between the key and the value.
在这里,我假设这些值只是数字,并且键和值之间可以有一个空格。
Other option is to use split
and a Map
:
其他选项是使用split
和 a Map
:
Map<String, Integer> map = new HashMap<>();
for (String keyValue: json.split(",")) {
String[] data = keyValue.split(":");
map.put(
data[0].replace("\"", """),
Integer.valueOf(data[1].trim());
);
}
And later you just do map.get(key)
.
后来你就做map.get(key)
。
回答by Abdul Fatir
I don't know why you'd want to do this at all when you can parse the JSON using a parser but here it goes.
当您可以使用解析器解析 JSON 时,我不知道您为什么要这样做,但它就在这里。
String patternStr= key + "\":(\d+)";
Regex will be key
+\":(\d+)"
based on the input string you've shown us.
根据您向我们展示的输入字符串,正则表达式将是key
+ \":(\d+)"
。
USE A JSON PARSER, though.
不过,请使用 JSON 解析器。