Skip to content

Commit 27c6d90

Browse files
committed
feat: hex color pattern
1 parent 91663a7 commit 27c6d90

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/patterns/hex-color.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { buildRegExp } from '../builders';
2+
import { endOfString, startOfString } from '../constructs/anchors';
3+
import { charClass, charRange, digit } from '../constructs/character-class';
4+
import { choiceOf } from '../constructs/choice-of';
5+
import { optional } from '../constructs/quantifiers';
6+
import { repeat } from '../constructs/repeat';
7+
8+
const hexDigit = charClass(digit, charRange('a', 'f'));
9+
10+
/** Find hex color strings in a text. */
11+
export const hexColorFinder = buildRegExp(
12+
[
13+
'#',
14+
choiceOf(
15+
repeat(hexDigit, 6), // #rrggbb
16+
repeat(hexDigit, 3), // #rgb
17+
),
18+
],
19+
{ ignoreCase: true },
20+
);
21+
22+
/**
23+
* Check that given text is a valid hex color.
24+
*
25+
* Allows both 3 and 6 digit hex colors, with or without the leading `#`.
26+
* */
27+
export const hexColorValidator = buildRegExp(
28+
[
29+
startOfString, // Match whole string
30+
optional('#'),
31+
choiceOf(
32+
repeat(hexDigit, 6), // #rrggbb
33+
repeat(hexDigit, 3), // #rgb
34+
),
35+
endOfString,
36+
],
37+
{
38+
ignoreCase: true,
39+
},
40+
);

src/patterns/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { hexColorFinder, hexColorValidator } from './hex-color';

0 commit comments

Comments
 (0)