Skip to main content
On this page

@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

什么是 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

你找到了你需要的东西吗?

编辑此页面
隐私政策