0.0.1 • Published 5 months ago
cidr-to-regexp v0.0.1
cidr-to-regexp
cidr-to-regexp
is an npm module that converts CIDR (Classless Inter-Domain Routing) notation to regular expression. This can be useful for validating or matching IP addresses within a specified range. Created based on this gist (kudos for @ollyg & @radu-c).
Installation
You can install the module using npm:
npm i cidr-to-regexp
Usage
Here are some examples of how to use the cidr-to-regexp
module:
Example 1: Convert CIDR to RegExp
import cidrToRegexp from 'cidr-to-regexp';
const cidr = '192.168.0.0/24';
const regexp = cidrToRegexp(cidr);
console.log(regexp); // Output: /^192\.168\.0\.(?:1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])$/
Example 2: Validate an IP Address
import cidrToRegexp from 'cidr-to-regexp';
const cidr = '192.168.0.0/24';
const regexp = cidrToRegexp(cidr);
const ip = '192.168.0.1';
console.log(regexp.test(ip)); // Output: true
Example 3: Match IP Addresses in a Range
import cidrToRegexp from 'cidr-to-regexp';
const cidr = '10.0.0.0/8';
const regexp = cidrToRegexp(cidr);
const ips = ['10.0.0.1', '10.1.2.3', '192.168.1.1'];
const matchedIps = ips.filter(ip => regexp.test(ip));
console.log(matchedIps); // Output: ['10.0.0.1', '10.1.2.3']
API
cidrToRegexp(cidr)
cidr
(string): The CIDR notation to convert.- Returns: A
RegExp
object that matches IP addresses within the specified CIDR range.
0.0.1
5 months ago