Search code examples
javascriptregexipv4

What is proper JavaScript IPv4 regex excluding 0.0.0.0 and 255.255.255.255?


Could you guys let me know the proper regex for IPv4 (excluding 0.0.0.0 and 255.255.255.255) in JavaScript language?

Actually, my test regex is as below. But still 0.0.0.0 and 255.255.255.255 is matching.

So, is there better regex than mine ? and also any solution to exclude 0.0.0.0 and 255.255.255.255

Thanks in advance.


    function inputCheck(inputString) {
        var inputList = inputString.split("\n");
        var flagList = [];
        var ipRegex = new RegExp("^(([1-9]?\\d|1\\d\\d|2[0-5][0-5]|2[0-4]\\d)\\.){3}([1-9]?\\d|1\\d\\d|2[0-5][0-5]|2[0-4]\\d)$");

        for (var i=0; i<inputList.length; i++) {
            var tempResult = ipRegex.test(inputList[i]);
            flagList.push(tempResult);
        }

        if (inputString.replace(/\s/gi, "").length === 0) {
            return true;
        } else if(flagList.indexOf(false) !== -1) {
            return false;
        } else {
            return true;
        }
    }

Solution

  • This should work for you:

    ^(?!0\.0\.0\.0|255\.255\.255\.255)((((2([0-4][0-9]|5[0-5]))|1[0-9]{2}|[0-9]{1,2})\.){3}(((2([0-4][0-9]|5[0-5]))|1[0-9]{2}|[0-9]{1,2})))$

    • ^ - start
    • (?!0\.0\.0\.0|255\.255\.255\.255) - not 0.0.0.0 or 255.255.255.255
    • ((2([0-4][0-9]|5[0-5]))|1[0-9]{2}|[0-9]{1,2}) - 0-255
    • (((2([0-4][0-9]|5[0-5]))|1[0-9]{2}|[0-9]{1,2})\.){3} - 0-255 followed by a full stop, three times
    • (((2([0-4][0-9]|5[0-5]))|1[0-9]{2}|[0-9]{1,2})) - 0-255
    • $ - end

    Regular expression visualisation

    Debuggex Demo