UNPKG

12.1 kBMarkdownView Raw
1# to-regex-range [![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)
2
3> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.
4
5Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
6
7## Install
8
9Install with [npm](https://www.npmjs.com/):
10
11```sh
12$ npm install --save to-regex-range
13```
14
15<details>
16<summary><strong>What does this do?</strong></summary>
17
18<br>
19
20This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers.
21
22**Example**
23
24```js
25var toRegexRange = require('to-regex-range');
26var regex = new RegExp(toRegexRange('15', '95'));
27```
28
29A 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).
30
31<br>
32
33</details>
34
35<details>
36<summary><strong>Why use this library?</strong></summary>
37
38<br>
39
40### Convenience
41
42Creating regular expressions for matching numbers gets deceptively complicated pretty fast.
43
44For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc:
45
46* regex for matching `1` => `/1/` (easy enough)
47* regex for matching `1` through `5` => `/[1-5]/` (not bad...)
48* regex for matching `1` or `5` => `/(1|5)/` (still easy...)
49* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...)
50* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...)
51* 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...)
52* 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!)
53
54The 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.
55
56**Learn more**
57
58If 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.
59
60### Heavily tested
61
62As of July 04, 2018, this library runs [2,783,483 test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are indeed correct.
63
64Tests run in ~870ms on my MacBook Pro, 2.5 GHz Intel Core i7.
65
66### Highly optimized
67
68Generated regular expressions are highly optimized:
69
70* duplicate sequences and character classes are reduced using quantifiers
71* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative
72* uses fragment caching to avoid processing the same exact string more than once
73
74<br>
75
76</details>
77
78## Usage
79
80Add this library to your javascript application with the following line of code
81
82```js
83var toRegexRange = require('to-regex-range');
84```
85
86The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers).
87
88```js
89var source = toRegexRange('15', '95');
90//=> 1[5-9]|[2-8][0-9]|9[0-5]
91
92var re = new RegExp('^' + source + '$');
93console.log(re.test('14')); //=> false
94console.log(re.test('50')); //=> true
95console.log(re.test('94')); //=> true
96console.log(re.test('96')); //=> false
97```
98
99## Options
100
101### options.capture
102
103**Type**: `boolean`
104
105**Deafault**: `undefined`
106
107Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges.
108
109```js
110console.log(toRegexRange('-10', '10'));
111//=> -[1-9]|-?10|[0-9]
112
113console.log(toRegexRange('-10', '10', {capture: true}));
114//=> (-[1-9]|-?10|[0-9])
115```
116
117### options.shorthand
118
119**Type**: `boolean`
120
121**Deafault**: `undefined`
122
123Use the regex shorthand for `[0-9]`:
124
125```js
126console.log(toRegexRange('0', '999999'));
127//=> [0-9]|[1-9][0-9]{1,5}
128
129console.log(toRegexRange('0', '999999', {shorthand: true}));
130//=> \d|[1-9]\d{1,5}
131```
132
133### options.relaxZeros
134
135**Type**: `boolean`
136
137**Default**: `true`
138
139This option only applies to **negative zero-padded ranges**. By default, when a negative zero-padded range is defined, the number of leading zeros is relaxed using `-0*`.
140
141```js
142console.log(toRegexRange('-001', '100'));
143//=> -0*1|0{2}[0-9]|0[1-9][0-9]|100
144
145console.log(toRegexRange('-001', '100', {relaxZeros: false}));
146//=> -0{2}1|0{2}[0-9]|0[1-9][0-9]|100
147```
148
149<details>
150<summary><strong>Why are zeros relaxed for negative zero-padded ranges by default?</strong></summary>
151
152Consider the following.
153
154```js
155var regex = toRegexRange('-001', '100');
156```
157
158_Note that `-001` and `100` are both three digits long_.
159
160In most zero-padding implementations, only a single leading zero is enough to indicate that zero-padding should be applied. Thus, the leading zeros would be "corrected" on the negative range in the example to `-01`, instead of `-001`, to make total length of each string no greater than the length of the largest number in the range (in other words, `-001` is 4 digits, but `100` is only three digits).
161
162If zeros were not relaxed by default, you might expect the resulting regex of the above pattern to match `-001` - given that it's defined that way in the arguments - _but it wouldn't_. It would, however, match `-01`. This gets even more ambiguous with large ranges, like `-01` to `1000000`.
163
164Thus, we relax zeros by default to provide a more predictable experience for users.
165
166</details>
167
168## Examples
169
170| **Range** | **Result** | **Compile time** |
171| --- | --- | --- |
172| `toRegexRange('5, 5')` | `5` | _15μs_
173 |
174| `toRegexRange('5, 6')` | `5\ | 6` | _21μs_
175 |
176| `toRegexRange('29, 51')` | `29\ | [34](https://github.com//0-9)\ | 5[01]` | _314μs_
177 |
178| `toRegexRange('31, 877')` | `3[1-9]\ | [4-9](https://github.com//0-9)\ | [1-7](https://github.com//0-92)\ | 8[0-6](https://github.com//0-9)\ | 87[0-7]` | _88μs_
179 |
180| `toRegexRange('111, 555')` | `11[1-9]\ | 1[2-9](https://github.com//0-9)\ | [2-4](https://github.com//0-92)\ | 5[0-4](https://github.com//0-9)\ | 55[0-5]` | _72μs_
181 |
182| `toRegexRange('-10, 10')` | `-[1-9]\ | -?10\ | [0-9](https://github.com//0-9)` | _67μs_
183 |
184| `toRegexRange('-100, -10')` | `-1[0-9](https://github.com//0-9)\ | -[2-9](https://github.com//0-9)\ | -100` | _53μs_
185 |
186| `toRegexRange('-100, 100')` | `-[1-9]\ | -?[1-9](https://github.com//0-9)\ | -?100\ | [0-9](https://github.com//0-9)` | _68μs_
187 |
188| `toRegexRange('001, 100')` | `0{2}[1-9]\ | 0[1-9](https://github.com//0-9)\ | 100` | _121μs_
189 |
190| `toRegexRange('0010, 1000')` | `0{2}1[0-9](https://github.com//0-9)\ | 0{2}[2-9](https://github.com//0-9)\ | 0[1-9](https://github.com//0-92)\ | 1000` | _73μs_
191 |
192| `toRegexRange('1, 2')` | `1\ | 2` | _10μs_
193 |
194| `toRegexRange('1, 5')` | `[1-5]` | _26μs_
195 |
196| `toRegexRange('1, 10')` | `[1-9]\ | 10` | _33μs_
197 |
198| `toRegexRange('1, 100')` | `[1-9]\ | [1-9](https://github.com//0-9)\ | 100` | _67μs_
199 |
200| `toRegexRange('1, 1000')` | `[1-9]\ | [1-9](https://github.com//0-91,2)\ | 1000` | _50μs_
201 |
202| `toRegexRange('1, 10000')` | `[1-9]\ | [1-9](https://github.com//0-91,3)\ | 10000` | _65μs_
203 |
204| `toRegexRange('1, 100000')` | `[1-9]\ | [1-9](https://github.com//0-91,4)\ | 100000` | _69μs_
205 |
206| `toRegexRange('1, 1000000')` | `[1-9]\ | [1-9](https://github.com//0-91,5)\ | 1000000` | _74μs_
207 |
208| `toRegexRange('1, 10000000')` | `[1-9]\ | [1-9](https://github.com//0-91,6)\ | 10000000` | _86μs_
209 |
210
211## Heads up!
212
213**Order of arguments**
214
215When the `min` is larger than the `max`, values will be flipped to create a valid range:
216
217```js
218toRegexRange('51', '29');
219```
220
221Is effectively flipped to:
222
223```js
224toRegexRange('29', '51');
225//=> 29|[3-4][0-9]|5[0-1]
226```
227
228**Steps / increments**
229
230This library does not support steps (increments). A pr to add support would be welcome.
231
232## History
233
234### v2.0.0 - 2017-04-21
235
236**New features**
237
238Adds support for zero-padding!
239
240### v1.0.0
241
242**Optimizations**
243
244Repeating 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.
245
246## Attribution
247
248Inspired by the python library [range-regex](https://github.com/dimka665/range-regex).
249
250## About
251
252<details>
253<summary><strong>Contributing</strong></summary>
254
255Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
256
257</details>
258
259<details>
260<summary><strong>Running Tests</strong></summary>
261
262Running 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:
263
264```sh
265$ npm install && npm test
266```
267
268</details>
269
270<details>
271<summary><strong>Building docs</strong></summary>
272
273_(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.)_
274
275To generate the readme, run the following command:
276
277```sh
278$ npm install -g verbose/verb#dev verb-generate-readme && verb
279```
280
281</details>
282
283### Related projects
284
285You might also be interested in these projects:
286
287* [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].")
288* [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`")
289* [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.")
290* [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.")
291* [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.")
292
293### Contributors
294
295| **Commits** | **Contributor** |
296| --- | --- |
297| 56 | [jonschlinkert](https://github.com/jonschlinkert) |
298| 2 | [realityking](https://github.com/realityking) |
299
300### Author
301
302**Jon Schlinkert**
303
304* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
305* [GitHub Profile](https://github.com/jonschlinkert)
306* [Twitter Profile](https://twitter.com/jonschlinkert)
307
308### License
309
310Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
311Released under the [MIT License](LICENSE).
312
313***
314
315_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 04, 2018._
\No newline at end of file