| 1 | /** |
| 2 | * Tools for working with JavaScript regular expressions from the Effect module |
| 3 | * namespace. The module exposes the native `RegExp` constructor, a guard for |
| 4 | * narrowing unknown values, and escaping for literal text that will be embedded |
| 5 | * in a pattern. |
| 6 | * |
| 7 | * Reach for `RegExp` when you need to build a regular expression from user or |
| 8 | * data-driven text, check whether an unknown value is already a `RegExp`, or |
| 9 | * access the native constructor without leaving the Effect namespace. |
| 10 | * |
| 11 | * @since 2.0.0 |
| 12 | */ |
| 13 | import * as predicate from "./Predicate.ts" |
| 14 | |
| 15 | /** |
| 16 | * Exposes the JavaScript regular expression constructor from `globalThis`. |
| 17 | * |
| 18 | * **When to use** |
| 19 | * |
| 20 | * Use to construct JavaScript regular expressions through the Effect module |
| 21 | * namespace. |
| 22 | * |
| 23 | * **Example** (Creating a regular expression) |
| 24 | * |
| 25 | * ```ts import.meta.vitest |
| 26 | * import { RegExp } from "effect" |
| 27 | * |
| 28 | * const pattern = new RegExp.RegExp("hello", "i") |
| 29 | * pattern // => /hello/i |
| 30 | * pattern.test("Hello World") // => true |
| 31 | * pattern.test("goodbye") // => false |
| 32 | * ``` |
| 33 | * |
| 34 | * @category constructors |
| 35 | * @since 4.0.0 |
| 36 | */ |
| 37 | export const RegExp = globalThis.RegExp |
| 38 | |
| 39 | /** |
| 40 | * Checks whether a value is a `RegExp`. |
| 41 | * |
| 42 | * **When to use** |
| 43 | * |
| 44 | * Use to validate unknown input before treating it as a regular expression. |
| 45 | * |
| 46 | * **Example** (Checking for regular expressions) |
| 47 | * |
| 48 | * ```ts import.meta.vitest |
| 49 | * import { RegExp } from "effect" |
| 50 | * |
| 51 | * RegExp.isRegExp(/a/) // => true |
| 52 | * RegExp.isRegExp("a") // => false |
| 53 | * ``` |
| 54 | * |
| 55 | * @category guards |
| 56 | * @since 3.9.0 |
| 57 | */ |
| 58 | export const isRegExp: (input: unknown) => input is RegExp = predicate.isRegExp |
| 59 | |
| 60 | /** |
| 61 | * Escapes special characters in a regular expression pattern. |
| 62 | * |
| 63 | * **When to use** |
| 64 | * |
| 65 | * Use to turn literal text into a safe regular expression pattern fragment. |
| 66 | * |
| 67 | * **Example** (Escaping a pattern string) |
| 68 | * |
| 69 | * ```ts import.meta.vitest |
| 70 | * import { RegExp } from "effect" |
| 71 | * |
| 72 | * RegExp.escape("a*b") // => "a\\*b" |
| 73 | * ``` |
| 74 | * |
| 75 | * @category transforming |
| 76 | * @since 2.0.0 |
| 77 | */ |
| 78 | export const escape = (string: string): string => string.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&") |