-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
24 lines (19 loc) · 1.01 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import ipRegex from "ip-regex";
type Options = {
/**
Only match an exact string. Useful with `RegExp#test()` to check if a string is an IP address. *(`false` matches any IP address in a string)*
@default false
*/
readonly exact?: boolean;
}
const defaultOpts: Options = {exact: false};
const v4str = `${ipRegex.v4().source}\\/(3[0-2]|[12]?[0-9])`;
const v6str = `${ipRegex.v6().source}\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])`;
// pre-compile only the exact regexes as global flag makes regex objects stateful
const v4exact = new RegExp(`^${v4str}$`);
const v6exact = new RegExp(`^${v6str}$`);
const v46exact = new RegExp(`(?:^${v4str}$)|(?:^${v6str}$)`);
const cidrRegex = ({exact}: Options = defaultOpts) => exact ? v46exact : new RegExp(`(?:${v4str})|(?:${v6str})`, "g");
export const v4 = cidrRegex.v4 = ({exact}: Options = defaultOpts) => exact ? v4exact : new RegExp(v4str, "g");
export const v6 = cidrRegex.v6 = ({exact}: Options = defaultOpts) => exact ? v6exact : new RegExp(v6str, "g");
export default cidrRegex;