@std/regexp
Overview Jump to heading
Functions for tasks related to regular expression (regexp), such as escaping text for interpolation into a regexp.
import { escape } from "@std/regexp/escape";
import { assertEquals, assertMatch, assertNotMatch } from "@std/assert";
const re = new RegExp(`^${escape(".")}$`, "u");
assertEquals("^\\.$", re.source);
assertMatch(".", re);
assertNotMatch("a", re);
Add to your project Jump to heading
deno add jsr:@std/regexp
See all symbols in @std/regexp on
What is RegExp? Jump to heading
RegExp (regular expressions) are patterns used to match character combinations
in strings. In JavaScript, they are implemented via the RegExp
object and
literal syntax (e.g., /pattern/flags
).
Why use @std/regexp? Jump to heading
This package provides small utilities to make working with regexps safer and easier:
- Use
escape()
when interpolating user input into a RegExp to avoid unintended meta-characters. - Prefer the
u
(unicode) flag for correctness; it changes how escapes and character classes behave. - Anchors:
^
and$
match start/end of string; usem
flag to make them line-based. - When performance matters, precompile your regex once and reuse it.
Examples Jump to heading
import { escape } from "@std/regexp/escape";
const user = "hello.+(world)";
const safe = new RegExp(`^${escape(user)}$`, "u");
safe.test("hello.+(world)"); // true
safe.test("helloX(world)"); // false
// Multiline anchors
const re = /^error:.+$/mu;
re.test("ok\nerror: bad\nnext"); // true