DEV Community

Discussion on: The beauty of VerbalExpressions

Collapse
 
inf3rno profile image
inf3rno • Edited

I think this is a very bad idea, it is much better to learn regex from regular-expressions.info.

I think having a single line complex regex is a code smell. It is a much better approach to build it from sub-patterns or use multiple regex patterns or don't use regex at all. I Have a small example as evidence (note that the code is not tested or not even written in an editor):

Using a single complex pattern (common golden hammer mistake):

function checkIP(address){
    if (!(/^(?:\d|[1-9]\d|1\d{2,2}|2[0-4]\d|25[0-5])(?:\.(?:\d|[1-9]\d|1\d{2,2}|2[0-4]\d|25[0-5])){3,3}$/).test(address))
        throw new InvalidIP();
}

Using multiple small patterns in combination with language features:

function checkIP(address){
    let parts = address.split(".");
    if (parts.length != 4)
        throw new InvalidIP();
    parts.forEach((part){
        if (!(/^\d{1,3}$/).test(part))
            throw new InvalidIP();
        if ((/^0./).test(part))
            throw new InvalidIP();
        let num = parseInt(part);
        if (num>255)
            throw new InvalidIP();
    });
}

Building the pattern from sub-patterns:

function checkIP(address){
    let lessThan256 = "(?:\d|[1-9]\d|1\d{2,2}|2[0-4]\d|25[0-5])";
    let pattern = `^${lessThan256}(?:\.${lessThan256}){3,3}$`;
    if (!(new RegExp(pattern)).test(address))
        throw new InvalidIP();
}