1

Following regex gives wrong result for ip address validation rvrn though regular expression is correct and gives correct result in node based running of .js code.

    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); 

    }
}
murphy
  • 11
  • 2
  • Updated details. Basically all being IP address and correct, each should have passed. But two input validation fails. – murphy Feb 12 '18 at 10:34

2 Answers2

0

Can you print the error log? Let me know what it says!

Also, try using the following regex:

var ipv4rgx = @"^((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.|$)){4}";
var ipv6rgx = "^([0-9a-fA-F]{1,4}(:|$)){8}";
  • there's no error. The match will just fail with result 'false'. Here requirement is not regex, i fail to understand why it doesn't work. Regex is correct, works fine in seperate javascript code. Then why not with script engine? – murphy Feb 12 '18 at 09:46
0

I can't tell you why this is happening, but it seems to be related to using the times modifier {3}. If you change your regular expression to

"^(?:\\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]))$"

(expanding the final {3} to three explicit expressions), then it seems to work as expected.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Thanks for ur time @khelwood, I have another regex that will work. Just want to root cause why this one fails? I don’t think it’s problem with expansion (i.e. {3}). For example following regex works fine: "^((\\d|1?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:\\d|1?\\d\\d|2[0-4]\\d|25[0-5])$"; //gives correct result – murphy Feb 12 '18 at 12:05
  • If I knew, I would tell you. Maybe it is a bug. – khelwood Feb 12 '18 at 12:08