我有以下 json 文档:
{
"videoUrl":"",
"available":"true",
"movie":{
"videoUrl":"http..."
},
"account":{
"videoUrl":"http...",
"login":"",
"password":""
}
}
在此 json 中,我有一个名为 videoUrl 的属性,我想获取第一个非空 videoUrl
我的正则表达式:
("videoUrl":)("http.+")
但是这个正则表达式匹配以下字符串
"videoUrl" :"http..."},
"account" : {"videoUrl" : "http...","login" : "","password" : ""
我编写正则表达式的方法是什么,它将找到第一个非空 videoUrl 及其值
(结果应为"videoUrl":"http..."
)
最佳答案
在正则表达式末尾添加 (?!,)
,这将使正则表达式停在 ,
处而不捕获它:
public static void main(String[] args) {
String input = "{ \n" +
" \"videoUrl\":\"\",\n" +
" \"available\":\"true\",\n" +
" \"movie\":{ \n" +
" \"videoUrl\":\"http...\"\n" +
" },\n" +
" \"account\":{ \n" +
" \"videoUrl\":\"http...\",\n" +
" \"login\":\"\",\n" +
" \"password\":\"\"\n" +
" }\n" +
"} ";
Pattern pattern = Pattern.compile("(\"videoUrl\":)(\"http.+\")(?!,)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group()); // "videoUrl":"http..."
}
}
关于java - 使用正则表达式从 json 获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50486394/