正则表达式搜索何时找到文本而其他文本丢失

我有以下文字:

application ONE {
    protocol tcp;
    destination-port 50;
}
application TWO {
    protocol udp;
    destination-port 51;
    inactivity-timeout 800;
}
application THREE {
    protocol udp;
    destination-port 500;
}

我需要搜索每个应用程序,当协议是udp时,如果不活动超时不同于1800(应用程序TWO)或协议是udp并且没有定义不活动(应用程序三).
我用正则表达式解决了第一个案例:

(?s)(?=protocol udp).*(inactivity-timeout (?!1800))

但我还没有办法获得第二个.

有什么建议?

最佳答案 你用Java标记了这一点,所以我给你一个Java解决方案,虽然我不确定你的帖子是否是你想要的.

我个人会将问题分成两部分.首先,提取应用程序,然后检查应用程序是否满足要求.这是我的尝试.

public class ApplicationReadOut {

    public static String EXAMLPLE = "application ONE {\r\n"
        +"    protocol tcp;\r\n"
        +"    destination-port 50;\r\n"
        +"}\r\n"
        +"application TWO {\r\n"
        +"    protocol udp;\r\n"
        +"    destination-port 51;\r\n"
        +"    inactivity-timeout 800;\r\n"
        +"}\r\n"
        +"application THREE {\r\n"
        +"    protocol udp;\r\n"
        +"    destination-port 500;\r\n"
        +"}\r\n";

    public boolean checkApplication(String app) {
        String[] lines = app.split("\r\n");
        boolean udp = false;
        boolean timeoutDiffers = true;
        boolean timeoutMentioned = false;
        for (String line : lines) {
            if (line.trim().equals("protocol udp;"))
                udp = true;
            if (line.trim().equals("inactivity-timeout 1800;"))
                timeoutDiffers = false;
            if (line.trim().startsWith("inactivity-timeout "))
                timeoutMentioned = true;
        }
        return udp & (timeoutDiffers | !timeoutMentioned);
    }

    public String[] extractApplications(String text) {
        String[] applications = text.split("}(\r*\n*)*"); 
        // the \r\n thing is to ignore blank lines in between applications
        ArrayList<String> goodApps = new ArrayList<String>(applications.length);
        for (int i = 0; i < applications.length; i++) {
            applications[i] += "}"; // this was removed by split
            if (checkApplication(applications[i]))
                goodApps.add(applications[i]);
        }
        return goodApps.toArray(new String[0]);
    }


    public static void main(String[] args) {
        ApplicationReadOut aro = new ApplicationReadOut();
        System.out.println(Arrays.toString(aro.extractApplications(EXAMLPLE)));
    }

}

我希望这很有用,你可以修改它以满足你的需求:-)

点赞