gpt4 book ai didi

java - 使用正则表达式从 json 获取字段

转载 作者:行者123 更新时间:2023-12-01 07:18:13 25 4
gpt4 key购买 nike

我有以下 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/

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