pax_global_header00006660000000000000000000000064134523113760014517gustar00rootroot0000000000000052 comment=1191a52afa82f52983e684ceeb8f8d3a150fa881 to-regex-range-5.0.1/000077500000000000000000000000001345231137600143465ustar00rootroot00000000000000to-regex-range-5.0.1/.editorconfig000066400000000000000000000004411345231137600170220ustar00rootroot00000000000000# http://editorconfig.org/ root = true [*] charset = utf-8 end_of_line = lf indent_size = 2 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [{**/{actual,fixtures,expected,templates}/**,*.md}] trim_trailing_whitespace = false insert_final_newline = false to-regex-range-5.0.1/.eslintrc.json000066400000000000000000000073251345231137600171510ustar00rootroot00000000000000{ "extends": [ "eslint:recommended" ], "env": { "browser": false, "es6": true, "node": true, "mocha": true }, "parserOptions":{ "ecmaVersion": 9, "sourceType": "module", "ecmaFeatures": { "modules": true, "experimentalObjectRestSpread": true } }, "globals": { "document": false, "navigator": false, "window": false }, "rules": { "accessor-pairs": 2, "arrow-spacing": [2, { "before": true, "after": true }], "block-spacing": [2, "always"], "brace-style": [2, "1tbs", { "allowSingleLine": true }], "comma-dangle": [2, "never"], "comma-spacing": [2, { "before": false, "after": true }], "comma-style": [2, "last"], "constructor-super": 2, "curly": [2, "multi-line"], "dot-location": [2, "property"], "eol-last": 2, "eqeqeq": [2, "allow-null"], "generator-star-spacing": [2, { "before": true, "after": true }], "handle-callback-err": [2, "^(err|error)$" ], "indent": [2, 2, { "SwitchCase": 1 }], "key-spacing": [2, { "beforeColon": false, "afterColon": true }], "keyword-spacing": [2, { "before": true, "after": true }], "new-cap": [2, { "newIsCap": true, "capIsNew": false }], "new-parens": 2, "no-array-constructor": 2, "no-caller": 2, "no-class-assign": 2, "no-cond-assign": 2, "no-const-assign": 2, "no-control-regex": 2, "no-debugger": 2, "no-delete-var": 2, "no-dupe-args": 2, "no-dupe-class-members": 2, "no-dupe-keys": 2, "no-duplicate-case": 2, "no-empty-character-class": 2, "no-eval": 2, "no-ex-assign": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-extra-boolean-cast": 2, "no-extra-parens": [2, "functions"], "no-fallthrough": 2, "no-floating-decimal": 2, "no-func-assign": 2, "no-implied-eval": 2, "no-inner-declarations": [2, "functions"], "no-invalid-regexp": 2, "no-irregular-whitespace": 2, "no-iterator": 2, "no-label-var": 2, "no-labels": 2, "no-lone-blocks": 2, "no-mixed-spaces-and-tabs": 2, "no-multi-spaces": 2, "no-multi-str": 2, "no-multiple-empty-lines": [2, { "max": 1 }], "no-native-reassign": 0, "no-negated-in-lhs": 2, "no-new": 2, "no-new-func": 2, "no-new-object": 2, "no-new-require": 2, "no-new-wrappers": 2, "no-obj-calls": 2, "no-octal": 2, "no-octal-escape": 2, "no-proto": 0, "no-redeclare": 2, "no-regex-spaces": 2, "no-return-assign": 2, "no-self-compare": 2, "no-sequences": 2, "no-shadow-restricted-names": 2, "no-spaced-func": 2, "no-sparse-arrays": 2, "no-this-before-super": 2, "no-throw-literal": 2, "no-trailing-spaces": 0, "no-undef": 2, "no-undef-init": 2, "no-unexpected-multiline": 2, "no-unneeded-ternary": [2, { "defaultAssignment": false }], "no-unreachable": 2, "no-unused-vars": [2, { "vars": "all", "args": "none" }], "no-useless-call": 0, "no-with": 2, "one-var": [0, { "initialized": "never" }], "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }], "padded-blocks": [0, "never"], "quotes": [2, "single", "avoid-escape"], "radix": 2, "semi": [2, "always"], "semi-spacing": [2, { "before": false, "after": true }], "space-before-blocks": [2, "always"], "space-before-function-paren": [2, "never"], "space-in-parens": [2, "never"], "space-infix-ops": 2, "space-unary-ops": [2, { "words": true, "nonwords": false }], "spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], "use-isnan": 2, "valid-typeof": 2, "wrap-iife": [2, "any"], "yoda": [2, "never"] } } to-regex-range-5.0.1/.gitattributes000066400000000000000000000002001345231137600172310ustar00rootroot00000000000000# Enforce Unix newlines * text eol=lf # binaries *.ai binary *.psd binary *.jpg binary *.gif binary *.png binary *.jpeg binary to-regex-range-5.0.1/.gitignore000066400000000000000000000004561345231137600163430ustar00rootroot00000000000000# always ignore files *.DS_Store .idea .vscode *.sublime-* # test related, or directories generated by tests test/actual actual coverage .nyc* # npm node_modules npm-debug.log # yarn yarn.lock yarn-error.log # misc _gh_pages _draft _drafts bower_components vendor temp tmp TODO.md package-lock.jsonto-regex-range-5.0.1/.npmrc000066400000000000000000000000231345231137600154610ustar00rootroot00000000000000package-lock=false to-regex-range-5.0.1/.travis.yml000066400000000000000000000001531345231137600164560ustar00rootroot00000000000000sudo: false os: - linux - osx - windows language: node_js node_js: - node - '10' - '9' - '8' to-regex-range-5.0.1/.verb.md000066400000000000000000000125661345231137600157160ustar00rootroot00000000000000
What does this do?
This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('{%= name %}'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string).
Why use this library?
### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: - regex for matching `1` => `/1/` (easy enough) - regex for matching `1` through `5` => `/[1-5]/` (not bad...) - regex for matching `1` or `5` => `/(1|5)/` (still easy...) - regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) - regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) - regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) - regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of {%= date() %}, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: - duplicate sequences and character classes are reduced using quantifiers - smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative - uses fragment caching to avoid processing the same exact string more than once
## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('{%= name %}'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples {%= examples() %} ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v5.0.0 - 2019-04-07 Optimizations. Updated code to use newer ES features. ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex).to-regex-range-5.0.1/LICENSE000066400000000000000000000021031345231137600153470ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015-present, Jon Schlinkert. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. to-regex-range-5.0.1/README.md000066400000000000000000000324211345231137600156270ustar00rootroot00000000000000# to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ```
What does this do?
This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('to-regex-range'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string).
Why use this library?
### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once
## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | | `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | | `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | | `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | | `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | | `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | | `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | | `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | | `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | | `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | | `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | | `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | | `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | | `toRegexRange(5, 5)` | `5` | _8μs_ | | `toRegexRange(5, 6)` | `5\|6` | _11μs_ | | `toRegexRange(1, 2)` | `1\|2` | _6μs_ | | `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | | `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | | `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | | `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | | `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | | `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | | `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | | `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About
Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Running Tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ```
Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ```
### Related projects You might also be interested in these projects: * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [doowb](https://github.com/doowb) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._to-regex-range-5.0.1/examples.js000066400000000000000000000025111345231137600165210ustar00rootroot00000000000000'use strict'; const toRegexRange = require('./'); const table = require('text-table'); const Time = require('time-diff'); const time = new Time(); /** * $ node examples.js */ const toRange = (min, max) => { let key = 'to-range' + min + max; time.start(key); return [ '', `\`toRegexRange(${min}, ${max})\``, `\`${toRegexRange(min, max, { wrap: false }).split('|').join('\\|')}\``, `_${time.end(key)}_`, '' ]; }; toRange('1', '3'); let rows = [ ['', '**Range**', '**Result**', '**Compile time**', ''], ['', '--- ', '--- ', '---', ''], ]; let examples = [ ['-10', '10'], ['-100', '-10'], ['-100', '100'], ['001', '100'], ['001', '555'], ['0010', '1000'], ['1', '50'], ['1', '55'], ['1', '555'], ['1', '5555'], ['111', '555'], ['29', '51'], ['31', '877'], ['5', '5'], ['5', '6'], ['1', '2'], ['1', '5'], ['1', '10'], ['1', '100'], ['1', '1000'], ['1', '10000'], ['1', '100000'], ['1', '1000000'], ['1', '10000000'], ].forEach(args => { rows.push(toRange.apply(null, args)); }); let text = table(rows, { hsep: ' | ' }); console.log(text); /** * This method is exposed as a helper, which is picked up * by verb and used in the .verb.md readme template */ module.exports = () => { return text.split('\n').map(line => line.replace(/^ +/, '')).join('\n'); }; to-regex-range-5.0.1/index.js000066400000000000000000000145211345231137600160160ustar00rootroot00000000000000/*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives, opts); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; let intersected = filterPatterns(neg, pos, '-?', true, options) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit, options); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ module.exports = toRegexRange; to-regex-range-5.0.1/package.json000066400000000000000000000033661345231137600166440ustar00rootroot00000000000000{ "name": "to-regex-range", "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", "version": "5.0.1", "homepage": "https://github.com/micromatch/to-regex-range", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ "Jon Schlinkert (http://twitter.com/jonschlinkert)", "Rouven Weßling (www.rouvenwessling.de)" ], "repository": "micromatch/to-regex-range", "bugs": { "url": "https://github.com/micromatch/to-regex-range/issues" }, "license": "MIT", "files": [ "index.js" ], "main": "index.js", "engines": { "node": ">=8.0" }, "scripts": { "test": "mocha" }, "dependencies": { "is-number": "^7.0.0" }, "devDependencies": { "fill-range": "^6.0.0", "gulp-format-md": "^2.0.0", "mocha": "^6.0.2", "text-table": "^0.2.0", "time-diff": "^0.3.1" }, "keywords": [ "bash", "date", "expand", "expansion", "expression", "glob", "match", "match date", "match number", "match numbers", "match year", "matches", "matching", "number", "numbers", "numerical", "range", "ranges", "regex", "regexp", "regular", "regular expression", "sequence" ], "verb": { "layout": "default", "toc": false, "tasks": [ "readme" ], "plugins": [ "gulp-format-md" ], "lint": { "reflinks": true }, "helpers": { "examples": { "displayName": "examples" } }, "related": { "list": [ "expand-range", "fill-range", "micromatch", "repeat-element", "repeat-string" ] } } } to-regex-range-5.0.1/test/000077500000000000000000000000001345231137600153255ustar00rootroot00000000000000to-regex-range-5.0.1/test/test.js000066400000000000000000000326601345231137600166510ustar00rootroot00000000000000'use strict'; require('mocha'); const assert = require('assert').strict; const fill = require('fill-range'); const toRange = require('..'); let count = 0; const inRange = (min, max, num) => min <= num && max >= num; const toRegex = str => new RegExp(`^${str}$`); const toRangeRegex = (min, max, options) => { return toRegex(toRange(min, max, { wrap: true, ...options })); }; const matcher = (...args) => { const regex = toRangeRegex(...args); return num => regex.test(String(num)); }; const matchRange = (min, max, expected, match, notMatch) => { if (max - min >= 1000000) { throw new RangeError('range is too big'); } let actual = toRange(min, max); let msg = actual + ' => ' + expected; // test expected string assert.equal(actual, expected, msg); let re = toRegex(actual); for (let i = 0; i < match.length; i++) { assert(re.test(match[i]), 'should match ' + msg); count++; } if (!Array.isArray(notMatch)) return; for (let j = 0; j < notMatch.length; j++) { assert(!re.test(notMatch[j]), 'should not match ' + msg); count++; } } const verifyRange = (min, max, from, to) => { let isMatch = matcher(min, max); let minNum = Math.min(min, max); let maxNum = Math.max(min, max); let num = from - 1; while (++num < to) { let n = Number(num); if (inRange(minNum, maxNum, n)) { assert(isMatch(num), `should match "${num}"`); } else { assert(!isMatch(num), `should not match "${num}"`); } count++; } }; const verifyZeros = (min, max, from, to) => { let range = fill(from, to); let len = range.length; let idx = -1; let isMatch = matcher(min, max); let minNum = Math.min(min, max); let maxNum = Math.max(min, max); while (++idx < len) { let num = range[idx]; let n = Number(num); if (inRange(minNum, maxNum, n)) { assert(isMatch(num), `should match "${num}"`); } else { assert(!isMatch(num), `should not match "${num}"`); } count++; } }; describe('to-regex-range', () => { after(() => { console.log(); console.log(' ', (+(+count.toFixed(2))).toLocaleString(), 'assertions'); }); describe('range', () => { it('should throw an error when the first arg is invalid:', () => { assert.throws(() => toRange(), /expected/); }); it('should throw an error when the second arg is invalid:', () => { assert.throws(() => toRange(1, {}), /expected/); }); it('should match the given numbers', () => { let oneFifty = toRegex(toRange(1, 150)); assert(oneFifty.test('125')); assert(!oneFifty.test('0')); assert(oneFifty.test('1')); assert(oneFifty.test('126')); assert(oneFifty.test('150')); assert(!oneFifty.test('151')); let oneTwentyFive = toRegex(toRange(1, 125)); assert(oneTwentyFive.test('125')); assert(!oneTwentyFive.test('0')); assert(oneTwentyFive.test('1')); assert(!oneTwentyFive.test('126')); assert(!oneTwentyFive.test('150')); assert(!oneTwentyFive.test('151')); }); }); describe('minimum / maximum', () => { it('should reverse `min/max` when the min is larger than the max:', () => { assert.equal(toRange(55, 10), '(?:1[0-9]|[2-4][0-9]|5[0-5])'); }); }); describe('ranges', () => { it('should return the number when only one argument is passed:', () => { assert.equal(toRange(5), '5'); }); it('should return a single number when both numbers are equal', () => { assert.equal(toRange('1', '1'), '1'); assert.equal(toRange('65443', '65443'), '65443'); assert.equal(toRange('192', '192'), '192'); verifyRange(1, 1, 0, 100); verifyRange(65443, 65443, 65000, 66000); verifyRange(192, 192, 0, 1000); }); it('should not return a range when both numbers are the same:', () => { assert.equal(toRange(5, 5), '5'); }); it('should return regex character classes when both args are less than 10', () => { assert.equal(toRange(0, 9), '[0-9]'); assert.equal(toRange(1, 5), '[1-5]'); assert.equal(toRange(1, 7), '[1-7]'); assert.equal(toRange(2, 6), '[2-6]'); }); it('should support string numbers', () => { assert.equal(toRange('1', '5'), '[1-5]'); assert.equal(toRange('10', '50'), '(?:1[0-9]|[2-4][0-9]|50)'); }); it('should support padded ranges:', () => { assert.equal(toRange('001', '005'), '0{0,2}[1-5]'); assert.equal(toRange('01', '05'), '0?[1-5]'); assert.equal(toRange('001', '100'), '(?:0{0,2}[1-9]|0?[1-9][0-9]|100)'); assert.equal(toRange('0001', '1000'), '(?:0{0,3}[1-9]|0{0,2}[1-9][0-9]|0?[1-9][0-9]{2}|1000)'); }); it('should work when padding is imbalanced:', () => { assert.equal(toRange('001', '105'), '(?:0{0,2}[1-9]|0?[1-9][0-9]|10[0-5])'); assert.equal(toRange('01', '105'), '(?:0{0,2}[1-9]|0?[1-9][0-9]|10[0-5])'); assert.equal(toRange('010', '105'), '(?:0?1[0-9]|0?[2-9][0-9]|10[0-5])'); assert.equal(toRange('010', '1005'), '(?:0{0,2}1[0-9]|0{0,2}[2-9][0-9]|0?[1-9][0-9]{2}|100[0-5])'); assert.equal(toRange('0001', '1000'), toRange('001', '1000')); assert.equal(toRange('0001', '1000'), toRange('01', '1000')); }); it('should generate regex strings for negative patterns', () => { assert.equal(toRange(-1, 0), '(?:-1|0)'); assert.equal(toRange(-1, 1), '(?:-1|[01])'); assert.equal(toRange(-4, -2), '-[2-4]'); assert.equal(toRange(-3, 1), '(?:-[1-3]|[01])'); assert.equal(toRange(-2, 0), '(?:-[12]|0)'); assert.equal(toRange(-1, 3), '(?:-1|[0-3])'); matchRange(-1, -1, '-1', [-1], [-2, 0, 1]); matchRange(-1, -10, '(?:-[1-9]|-10)', [-1, -5, -10], [-11, 0]); matchRange(-1, 3, '(?:-1|[0-3])', [-1, 0, 1, 2, 3], [-2, 4]); }); it('should wrap patterns when options.capture is true', () => { assert.equal(toRange(-1, 0, { capture: true }), '(-1|0)'); assert.equal(toRange(-1, 1, { capture: true }), '(-1|[01])'); assert.equal(toRange(-4, -2, { capture: true }), '(-[2-4])'); assert.equal(toRange(-3, 1, { capture: true }), '(-[1-3]|[01])'); assert.equal(toRange(-2, 0, { capture: true }), '(-[12]|0)'); assert.equal(toRange(-1, 3, { capture: true }), '(-1|[0-3])'); }); it('should generate regex strings for positive patterns', () => { assert.equal(toRange(1, 1), '1'); assert.equal(toRange(0, 1), '(?:0|1)'); assert.equal(toRange(0, 2), '[0-2]'); assert.equal(toRange(65666, 65667), '(?:65666|65667)'); assert.equal(toRange(12, 3456), '(?:1[2-9]|[2-9][0-9]|[1-9][0-9]{2}|[12][0-9]{3}|3[0-3][0-9]{2}|34[0-4][0-9]|345[0-6])'); assert.equal(toRange(1, 3456), '(?:[1-9]|[1-9][0-9]{1,2}|[12][0-9]{3}|3[0-3][0-9]{2}|34[0-4][0-9]|345[0-6])'); assert.equal(toRange(1, 10), '(?:[1-9]|10)'); assert.equal(toRange(1, 19), '(?:[1-9]|1[0-9])'); assert.equal(toRange(1, 99), '(?:[1-9]|[1-9][0-9])'); assert.equal(toRange(1, 100), '(?:[1-9]|[1-9][0-9]|100)'); assert.equal(toRange(1, 1000), '(?:[1-9]|[1-9][0-9]{1,2}|1000)'); assert.equal(toRange(1, 10000), '(?:[1-9]|[1-9][0-9]{1,3}|10000)'); assert.equal(toRange(1, 100000), '(?:[1-9]|[1-9][0-9]{1,4}|100000)'); assert.equal(toRange(1, 9999999), '(?:[1-9]|[1-9][0-9]{1,6})'); assert.equal(toRange(99, 100000), '(?:99|[1-9][0-9]{2,4}|100000)'); matchRange(99, 100000, '(?:99|[1-9][0-9]{2,4}|100000)', [99, 999, 989, 100, 9999, 9899, 10009, 10999, 100000], [0, 9, 100001, 100009]); }); it('should optimize regexes', () => { assert.equal(toRange(-9, 9), '(?:-[1-9]|[0-9])'); assert.equal(toRange(-19, 19), '(?:-[1-9]|-?1[0-9]|[0-9])'); assert.equal(toRange(-29, 29), '(?:-[1-9]|-?[12][0-9]|[0-9])'); assert.equal(toRange(-99, 99), '(?:-[1-9]|-?[1-9][0-9]|[0-9])'); assert.equal(toRange(-999, 999), '(?:-[1-9]|-?[1-9][0-9]{1,2}|[0-9])'); assert.equal(toRange(-9999, 9999), '(?:-[1-9]|-?[1-9][0-9]{1,3}|[0-9])'); assert.equal(toRange(-99999, 99999), '(?:-[1-9]|-?[1-9][0-9]{1,4}|[0-9])'); }); }); describe('validate ranges', () => { it('should match all numbers in the given range', () => { let isMatch = matcher(1, 59); for (let i = 0; i < 100; i++) { if (i >= 1 && i <= 59) { assert(isMatch(i)); } else { assert(!isMatch(i)); } } }); it('should support negative ranges:', () => { verifyRange(-9, -1, -100, 100); verifyRange(-99, -1, -1000, 1000); verifyRange(-999, -1, -1000, 1000); verifyRange(-9999, -1, -10000, 10000); verifyRange(-99999, -1, -100999, 100999); }); it('should support negative-to-positive ranges:', () => { verifyRange(-9, 9, -100, 100); verifyRange(-99, 99, -1000, 1000); verifyRange(-999, 999, -1000, 1000); verifyRange(-9999, 9999, -10000, 10000); verifyRange(-99999, 99999, -100999, 100999); }); it('should support large numbers:', () => { verifyRange(100019999300000, 100020000300000, 1000199992999900, 100020000200000); }); it('should support large ranges:', () => { verifyRange(1, 100000, 1, 1000); verifyRange(1, 100000, 10000, 11000); verifyRange(1, 100000, 99000, 100000); verifyRange(1, 100000, 1000, 2000); verifyRange(1, 100000, 10000, 12000); verifyRange(1, 100000, 50000, 60000); verifyRange(1, 100000, 99999, 101000); verifyRange(10331, 20381, 0, 99999); }); it('should support repeated digits:', () => { verifyRange(111, 222, 0, 999); verifyRange(111, 333, 0, 999); verifyRange(111, 444, 0, 999); verifyRange(111, 555, 0, 999); verifyRange(111, 666, 0, 999); verifyRange(111, 777, 0, 999); verifyRange(111, 888, 0, 999); verifyRange(111, 999, 0, 999); verifyRange(0, 111, -99, 999); verifyRange(0, 222, -99, 999); verifyRange(0, 333, -99, 999); verifyRange(0, 444, -99, 999); verifyRange(0, 555, -99, 999); verifyRange(0, 666, -99, 999); verifyRange(0, 777, -99, 999); verifyRange(0, 888, -99, 999); verifyRange(0, 999, -99, 999); }); it('should support repeated zeros:', () => { verifyRange(10031, 20081, 0, 59999); verifyRange(10000, 20000, 0, 59999); }); it('should support zero one:', () => { verifyRange(10301, 20101, 0, 99999); verifyRange(101010, 101210, 101009, 101300); }); it('should support repeated ones:', () => { verifyRange(1, 11111, 0, 1000); verifyRange(1, 1111, 0, 1000); verifyRange(1, 111, 0, 1000); verifyRange(1, 11, 0, 1000); verifyRange(1, 1, 0, 1000); }); it('should support small diffs:', () => { verifyRange(102, 103, 0, 1000); verifyRange(102, 110, 0, 1000); verifyRange(102, 130, 0, 1000); }); it('should support random ranges:', () => { verifyRange(4173, 7981, 0, 99999); }); it('should support one digit numbers:', () => { verifyRange(3, 7, 0, 99); }); it('should support one digit at bounds:', () => { verifyRange(1, 9, 0, 1000); }); it('should support power of ten:', () => { verifyRange(1000, 8632, 0, 99999); }); it('should not match the negative of the same number', () => { verifyRange(1, 1000, -1000, 1000); verifyRange(1, 1000, '-1000', '1000'); }); it('should work with numbers of varying lengths:', () => { verifyRange(1030, 20101, 0, 99999); verifyRange(13, 8632, 0, 10000); }); it('should support small ranges:', () => { verifyRange(9, 11, 0, 100); verifyRange(19, 21, 0, 100); }); it('should support big ranges:', () => { verifyRange(90, 98009, 0, 98999); verifyRange(999, 10000, 1, 20000); }); it('should create valid regex ranges with zero-padding:', () => { verifyZeros('001', '100', '001', 100); verifyZeros('001', '100', '001', '100'); verifyZeros('0001', '1000', '01', 1000); verifyZeros('0001', '1000', '-01', 1000); verifyZeros('0001', '1000', '-099', '1000'); verifyZeros('0001', '1000', '-010', 1000); verifyZeros('0001', '1000', '-010', 1000); verifyZeros('0001', '1000', '0001', '1000'); verifyZeros('01', '1000', '-01', '1000'); verifyZeros('000000001', '1000', '-010', '1000'); verifyZeros('00000001', '1000', '-010', '1000'); verifyZeros('0000001', '1000', '-010', '1000'); verifyZeros('000001', '1000', '-010', '1000'); verifyZeros('00001', '1000', '-010', '1000'); verifyZeros('0001', '1000', '-010', '1000'); verifyZeros('001', '1000', '-010', '1000'); verifyZeros('01', '1000', '-010', '1000'); verifyZeros('0001', '1000', '-010', '1000'); }); it('should create valid regex ranges with negative padding:', () => { verifyZeros('-00001', '-1000', -1000, 1000); verifyZeros('-0001', '-1000', -1000, 1000); verifyZeros('-001', '-1000', -1000, 1000); verifyZeros('-01', '-1000', -1000, 1000); }); it('should create valid ranges with neg && pos zero-padding:', () => { verifyZeros('-01', '10', '-1', '01'); verifyZeros('-1000', '100', -1000, 1000); verifyZeros('-1000', '0100', '-010', '1000'); verifyZeros('-0100', '100', '-01', '100'); verifyZeros('-010', '100', '-01', '100'); verifyZeros('-01', '100', '-01', '100'); verifyZeros('-01000', '1000', '-010', '1000'); verifyZeros('-0100', '1000', '-010', '1000'); verifyZeros('-010', '1000', '-010', '1000'); verifyZeros('-01', '1000', '-010', '1000'); }); }); });