cidr-to-regex
v0.3.0
Published
Convert IPv4/IPv6 CIDR blocks into regular expressions
Readme
cidr-to-regex
Convert IPv4 and IPv6 CIDR blocks into regular expressions.
Install
pnpm add cidr-to-regexUsage
import { cidrToRegex } from "cidr-to-regex";
const regex = cidrToRegex("2001:db8::/48");
const ok = regex.test("2001:0db8:0000:0000:0000:0000:0000:0001");API
cidrToRegex(cidr: string, options?: CidrToRegexOptions): RegExp
type CidrToRegexOptions = {
anchored?: boolean; // default false
ignoreCase?: boolean; // default false
global?: boolean; // default false
};- Accepts IPv4 and IPv6 CIDR input.
- CIDR parsing is liberal (for example compressed IPv6 like
::ff/16and IPv4inet_atonshorthands like10.1/32are accepted). - CIDR network bits are normalized (host bits in the input address are ignored).
- By default, returned regex is not full-string anchored.
options.anchoredcontrols whether^...$anchors are included.options.ignoreCaseenables case-insensitive IPv6 matching (addsiflag).options.globaladds thegflag to the returned regex.- Output matching targets:
- IPv4: canonical dotted-decimal (
a.b.c.d, no leading zeros). - IPv6: canonical RFC 5952 text representation, including IPv4-mapped IPv6 addresses
- IPv4: canonical dotted-decimal (
Compatibility
- Node.js:
>=14 - Browser compatibility with default options (
anchored: false):- Chrome
67+ - Firefox
78+ - Safari
16.4+
- Chrome
- Browser compatibility with
anchored: true(no regex lookbehind requirement):- Chrome
67+ - Firefox
68+ - Safari
14+
- Chrome
Development
pnpm install
pnpm run checkLinting and formatting:
pnpm run lint
pnpm run lint:fix
pnpm run format
pnpm run format:checkFixture generation
pnpm run generate:fixtures
pnpm run generate:differential-fixturesThese scripts use Python's ipaddress module to generate deterministic test fixtures. The generated fixtures are committed; test execution itself is pure TypeScript.
Benchmark
pnpm run benchOptional environment variables:
BENCH_ITERS(default5000)BENCH_WARMUP(default300)
