基于ScriptEngine的'javascript'进行错误的正则表达式验证(对于IP地址)

时间:2018-02-12 09:03:26

标签: javascript java scriptengine javascript-engine

以下正则表达式为ip地址验证提供了错误的结果rvrn虽然正则表达式是正确的,并且在基于节点的.js代码运行中给出了正确的结果。

    public static void excuteWithinEngine() throws ScriptException{

    // ip address regex
    String regEx = "^(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5])(?:\\.(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5])){3}$"; 

    Set<String> in=new HashSet<String>();
    //IPv4 A:B:C:D. if more than one chars are at position B,C then jsvascript based regex-test fails
    in.add("10.2.2.2");//output: true. (correct result)
    in.add("10.2.13.2");//output: false. (incorrect result)
    in.add("10.2.13.25");//output: false. (incorrect result)
    in.add("10.2.2.25");//output: true. (correct result)

    for(String input:in){

        String s = input;
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine se = factory.getEngineByName("JavaScript");
        se.put("regEx", regEx);
        se.put("string", s);
        se.eval("var RE = new RegExp(regEx);");
        boolean b= (boolean)se.eval("RE.test(string);"); // test function

        System.out.println("Testing "+s+" :"+b); 

    }
}

2 个答案:

答案 0 :(得分:0)

可以打印错误日志吗?让我知道它的内容!

另外,请尝试使用以下正则表达式:

var ipv4rgx = @"^((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.|$)){4}";
var ipv6rgx = "^([0-9a-fA-F]{1,4}(:|$)){8}";

答案 1 :(得分:0)

我不能告诉你为什么会这样,但它似乎与使用时间修饰符{3}有关。如果将正则表达式更改为

"^(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5])(?:\\.(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5]))(?:\\.(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5]))(?:\\.(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5]))$"

(将最终{3}扩展为三个显式表达式),然后它似乎按预期工作。