javascriptregexeslintcodacy

How to transform my regular expression detecting 127.0.0.1/8 IP to a safer one?


To detect all IP in the 127.0.0.1/8 network , I'm using this common regular expression:

/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/

Job is done, but codacy via es-lint is detecting this regexp as unsafe.

I already read this blog, this stackoverflow question, but I'm not fluent with regexp and I don't understand all explanations.

I tried to add [^,\r\n] in a lot of positions but it doesn't work.

Here is a tools to test the regexp: https://regex101.com/r/YbYrcd/1

Here is my javascript code detected as unsafe regexp by eslint:

window.location.hostname.match(
  /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)

How to transform the above regular expression to a safer one which is complient with eslint?


Solution

  • Eslint produces a warning because your regex contains a quantified group containing alternation operators and quantifiers inside. In reality, since the limiting quantifier only "repeats" the pattern three times, the pattern is rather safe, but Eslint cannot deduce that.

    To get rid of the warning, unwrap/unroll the quantified group (=repeat the . + octet pattern three times):

    /^127\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
    

    See the regex demo