gpt4 book ai didi

java - Beanshell 模式匹配器正则表达式

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

我有以下 JSON:

[
{
"": "",
"substituted_restday": "2020-02-01",
"original_restday": "2020-02-08",
"id": "15d13f70-c0a852c0-3a925f13-6dca1982",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13b7c65023",
"parentId": ""
},
{
"": "",
"substituted_restday": "2020-02-03",
"original_restday": "2020-02-09",
"id": "15d14d55-c0a852c0-3a925f13-727b70af",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13-3711a584",
"parentId": ""
}
]

我想从“substitute_restday”中提取“日期”,即 2020-02-01 和 2020-02-03。

我有以下代码,但结果不好:

Pattern pattern = Pattern.compile("((\"substituted_restday\":\")[0-9-]+)");
Matcher matcher = pattern.matcher(JSON);
System.out.println(matcher.find());
if (matcher.find()){
System.out.println(matcher.group(0));
System.out.println(matcher);
System.out.println("group count:" + matcher.groupCount());
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + ":" + matcher.group(i));
}
}

我可以看到“matcher.find()”是正确的。但 matcher.group 没有值(value)。请帮忙。

最佳答案

您必须循环匹配的模式,然后访问group(1):

public static void main(String[] args) {
Pattern pattern = Pattern.compile("\"substituted_restday\": \"([0-9-]+)\"");
Matcher matcher = pattern.matcher(JSON);
while(matcher.find()){
System.out.println(matcher.group(1));
}
}

输出将是:

2020-02-01
2020-02-03

如果您访问group(0),输出为:

 "substituted_restday": "2020-02-01"
"substituted_restday": "2020-02-03"

The groups are identified by the brackets

group(0): ("\"substituted_restday\": \"([0-9-]+)\"")

group(1): ([0-9-]+)

关于java - Beanshell 模式匹配器正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60089882/

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