Skip to content

Commit 1ab6f1a

Browse files
docs: add mixing with RegExp example (#60)
1 parent cfb3b8e commit 1ab6f1a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

docs/Examples.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,30 @@ const isValid = regex.test(192.168.0.1");
158158
Encoded regex: `/^(?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/`.
159159
160160
See tests: [example-ipv4.ts](../src/__tests__/example-ipv4.ts).
161+
162+
## Mixing with RegExp literals
163+
164+
```ts
165+
// Match integers from 0-255
166+
const octet = choiceOf(
167+
/[0-9]/, // 0-9
168+
/[1-9][0-9]/, // 10-99
169+
/1[0-9][0-9]/, // 100-199
170+
/2[0-4][0-9]/, // 200-249
171+
/25[0-5]/, // 250-255
172+
);
173+
174+
// Match
175+
const regex = buildRegExp([
176+
startOfString, //
177+
repeat([octet, '.'], 3),
178+
octet,
179+
endOfString,
180+
]);
181+
182+
const isValid = regex.test(192.168.0.1");
183+
```
184+
185+
Encoded regex: `/^(?:(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/,`.
186+
187+
See tests: [example-regexp.ts](../src/__tests__/example-regexp.ts).

src/__tests__/example-regexp.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { buildRegExp, choiceOf, endOfString, repeat, startOfString } from '../index';
2+
3+
test('example: mixing with RegExp literals (IPv4 address validator)', () => {
4+
const octet = choiceOf(
5+
/[0-9]/, // 0-9
6+
/[1-9][0-9]/, // 10-99
7+
/1[0-9][0-9]/, // 100-199
8+
/2[0-4][0-9]/, // 200-249
9+
/25[0-5]/, // 250-255
10+
);
11+
12+
const regex = buildRegExp([
13+
startOfString, // prettier break-line
14+
repeat([octet, '.'], 3),
15+
octet,
16+
endOfString,
17+
]);
18+
19+
expect(regex).toMatchString('0.0.0.0');
20+
expect(regex).toMatchString('192.168.0.1');
21+
expect(regex).toMatchString('1.99.100.249');
22+
expect(regex).toMatchString('255.255.255.255');
23+
expect(regex).toMatchString('123.45.67.89');
24+
25+
expect(regex).not.toMatchString('0.0.0.');
26+
expect(regex).not.toMatchString('0.0.0.0.');
27+
expect(regex).not.toMatchString('0.-1.0.0');
28+
expect(regex).not.toMatchString('0.1000.0.0');
29+
expect(regex).not.toMatchString('0.0.300.0');
30+
expect(regex).not.toMatchString('255.255.255.256');
31+
32+
expect(regex).toEqualRegex(
33+
/^(?:(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/,
34+
);
35+
});

0 commit comments

Comments
 (0)