On this page
@std/regexp
概述 Jump to heading
用于与 正则表达式(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);
添加到你的项目 Jump to heading
deno add jsr:@std/regexp
什么是 RegExp? Jump to heading
RegExp(正则表达式)是用于匹配字符串中字符组合的模式。在 JavaScript 中,通过 RegExp 对象和字面量语法(例如 /pattern/flags)实现。
为什么使用 @std/regexp? Jump to heading
该包提供了小型工具,使处理正则表达式更安全、更简单:
- 在将用户输入插入正则表达式时使用
escape(),避免意外的元字符。 - 优先使用
u(unicode)标志以保证正确性;它会影响转义字符和字符类的行为。 - 锚点:
^和$匹配字符串的开始和结束;使用m标志使它们作用于行。 - 关注性能时,预先编译正则表达式并重复使用。
示例 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
// 多行锚点
const re = /^error:.+$/mu;
re.test("ok\nerror: bad\nnext"); // true