Skip to content

Commit

Permalink
perf: make ipv4 regex faster
Browse files Browse the repository at this point in the history
All credits for this regex to https://stackoverflow.com/a/36760050. 

The regex is both more correct and faster (https://esbench.com/bench/6532596e7ff73700a4debb6a).
Examples:
previous regex recognized "01.01.01.01" or "1.1.000.1" as correct ipv4 regex, but those aren't valid as per https://datatracker.ietf.org/doc/html/rfc5954#section-4.1.
  • Loading branch information
kurtextrem authored Oct 20, 2023
1 parent 77b659c commit fe523c4
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { HEX } = require('./scopedChars')

function normalizeIPv4 (host) {
if (findToken(host, '.') < 3) { return { host, isIPV4: false } }
const matches = host.match(/^(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) || []
const matches = host.match(/^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/) || []
const [address] = matches
if (address) {
return { host: stripLeadingZeros(address, '.'), isIPV4: true }
Expand Down

0 comments on commit fe523c4

Please sign in to comment.