简体   繁体   English

在Java中定义模式从json字符串中提取多个日期的问题

[英]Problems defining the pattern to extract multiple dates from a json string in java

I have the following code: 我有以下代码:

    public static void main(String[] args) {
    String str = "{\"$and\":[{\\\"$or\\\":[{\\\"origen\\\":{\\\"$eq\\\":\\\"LEMD\\\"}},{\\\"origen\\\":{\\\"$eq\\\":\\\"LEBL\\\"}}]},{\"horasacta\":{\"$gte\":\"28/02/2015 00:00:00\"}},{\"horasacta\":{\"$lte\":\"28/02/2015 23:59:59\"}}]}";

    Pattern pattern = Pattern.compile("\\{\"(.*?)\":\\{\"\\$(.*?)\":\"[0-9]+/[0-9]+/[0-9]+ [0-9]+:[0-9]+:[0-9]+\"}}");
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        System.out.println(matcher.group(0));
    }

I want to get the substrings: 我想获取子字符串:

{\"departure\":{\"$gte\":\"28/02/2015 00:00:00\"}}
{\"departure\":{\"$lte\":\"28/02/2015 23:59:59\"}}

but the program give me: 但是程序给我:

{"$and":[{\"$or\":[{\"origin\":{\"$eq\":\"LEMD\"}},{\"origin\":{\"$eq\":\"LEBL\"}}]},{"departure":{"$gte":"28/02/2015 00:00:00"}}
{"departure":{"$lte":"28/02/2015 23:59:59"}}

the 2nd time the find() matches the pattern but the 1st time it doesn't do the job. 第二次,find()匹配模式,但是第一次,它没有完成任务。

Any help? 有什么帮助吗?

thanks 谢谢

It's frowned upon, yet if you have to, I'm guessing that you may be trying to write an expression looking somewhat like: 对此不满意,但如果您必须的话,我想您可能正在尝试编写类似以下内容的表达式:

{\\"([^\\]+)\\":{\\"\$([^\\]+)\\":\\"[0-9]+\/[0-9]+\/[0-9]+\s+[0-9]+:[0-9]+:[0-9]+\\"}}

not so sure though. 虽然不太确定。


The expression is explained on the top right panel of regex101.com , if you wish to explore/simplify/modify it, and in this link , you can watch how it would match against some sample inputs, if you like. regex101.com的右上角对表达式进行了说明,如果您希望对其进行探索/简化/修改,并且在此链接中 ,您可以根据需要观看它与某些示例输入的匹配方式。

Test 测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\{\\\\\"([^\\\\]+)\\\\\":\\{\\\\\"\\$([^\\\\]+)\\\\\":\\\\\"[0-9]+\\/[0-9]+\\/[0-9]+\\s+[0-9]+:[0-9]+:[0-9]+\\\\\"\\}}";
final String string = "{\\\"departure\\\":{\\\"$gte\\\":\\\"28/02/2015 00:00:00\\\"}}\n"
     + "{\\\"departure\\\":{\\\"$lte\\\":\\\"28/02/2015 23:59:59\\\"}}";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM