to-regex-range is a utility library that generates a regex-compatible source string for matching numeric ranges. It simplifies the complex task of creating regular expressions for ranges like '1 to 50' or '0001 to 5555', which can quickly become unwieldy to write manually. The current stable version is 5.0.1. While a specific release cadence isn't published, the library maintains a stable API. Key differentiators include its convenience in abstracting complex regex logic, extensive test validation (over 2.78 million assertions), and optimizations that produce smaller, efficient regular expressions by reducing duplicate sequences and utilizing fragment caching. It handles zero-padding and negative numbers, making it robust for various validation or parsing scenarios.
npm install to-regex-rangeVerified import paths — ran on the pinned version, not inferred.
Demonstrates generating a regex string for a numeric range, creating a RegExp object, and testing various numbers. Also shows how to use options like `relaxZeros` for specific padding requirements.
Always wrap the output in `new RegExp()`: `const regex = new RegExp(toRegexRange(min, max));`
Apply anchors to the generated source: `const regex = new RegExp(`^${toRegexRange(min, max)}$`);`For strict zero-padding, pass `{ relaxZeros: false }` in the options object: `toRegexRange('001', '010', { relaxZeros: false });`For stepped ranges, additional filtering or a different approach is needed after matching the broad range, or a custom regex must be constructed manually.
Use a default import: `import toRegexRange from 'to-regex-range';` or CommonJS `const toRegexRange = require('to-regex-range');`Ensure the generated source is wrapped with anchors: `const regex = new RegExp(`^${toRegexRange(min, max)}$`);`Adjust the `relaxZeros` option in the options object, typically setting `relaxZeros: false` for strict zero-padding: `toRegexRange('001', '010', { relaxZeros: false });`No dependency data recorded yet.