Z
ZHANK
实用技能

正则表达式

学习正则表达式语法与 String 方法

正则表达式

正则表达式是处理字符串的强大工具,用于搜索、匹配、替换。

学完本章你将: 掌握正则基础语法与 JS 的 RegExp 用法。


创建正则

javascript
// 字面量(推荐)
let re1 = /hello/g;

// 构造函数(动态生成时使用)
let re2 = new RegExp("hello", "g");

匹配模式

javascript
let str = "The fat cat sat on the mat.";

// test —— 返回布尔
console.log(/cat/.test(str));     // true
console.log(/dog/.test(str));     // false

// match —— 返回匹配结果
console.log(str.match(/at/g));    // ["at", "at", "at", "at"]

// search —— 返回索引(首次出现)
console.log(str.search(/cat/));   // 8

// replace —— 替换
console.log(str.replace(/cat/, "dog"));     // "The fat dog sat on the mat."
console.log(str.replace(/at/g, "AT"));      // "The fAT cAT sAT on the mAT."

// split —— 分割
console.log("a,b;c|d".split(/[,;|]/));     // ["a", "b", "c", "d"]

常用元字符

javascript
// 字符类
console.log(/\d/.test("5"));    // 数字
console.log(/\w/.test("a"));    // 字母数字下划线
console.log(/\s/.test(" "));    // 空白字符
console.log(/./.test("x"));     // 任意字符(除换行)

// 大写 = 取反
console.log(/\D/.test("a"));    // 非数字
console.log(/\W/.test("!"));    // 非字母数字
console.log(/\S/.test(" "));    // false(非空白)

// 自定义字符类
console.log(/[aeiou]/.test("hello"));  // 匹配任意元音
console.log(/[^aeiou]/.test("h"));    // 取反
console.log(/[a-z]/.test("m"));       // 范围

量词与锚点

javascript
// 量词
console.log(/a{3}/.test("aaa"));     // 恰好 3 次
console.log(/a{2,4}/.test("aaa"));   // 2-4 次
console.log(/a+/.test(""));          // 1 次或更多 → false
console.log(/a*/.test(""));          // 0 次或更多 → true
console.log(/colou?r/.test("color")); // u 可选 → true
console.log(/colou?r/.test("colour"));// true

// 锚点
console.log(/^start/.test("start here")); // 开头
console.log(/end$/.test("the end"));      // 结尾
console.log(/^exact$/.test("exact"));     // 完全匹配

// 分组
console.log(/(ha)+/.test("hahaha"));      // 重复分组

// 或
console.log(/cat|dog/.test("cat"));       // true

标志(Flags)

javascript
let str = "Hello hello HELLO";

// g —— 全局匹配
console.log(str.match(/hello/gi));  // ["Hello", "hello", "HELLO"]

// i —— 忽略大小写
console.log(/hello/i.test("HELLO"));// true

// m —— 多行模式(^$ 匹配每行开头结尾)
let multi = "line1\nline2\nline3";
console.log(multi.match(/^line/gm)); // ["line", "line", "line"]

// s —— dotAll(. 可匹配换行)
console.log(/a.b/s.test("a\nb"));   // true

常用正则示例

javascript
// 邮箱验证
let emailRe = /^[\w.-]+@[\w.-]+\.\w+$/;
console.log(emailRe.test("alice@example.com")); // true

// 手机号(中国)
let phoneRe = /^1[3-9]\d{9}$/;
console.log(phoneRe.test("13800138000")); // true

// 提取 URL 参数
let url = "https://example.com?name=Alice&age=25";
let params = Object.fromEntries(
    [...url.matchAll(/(\w+)=(\w+)/g)].map(m => [m[1], m[2]])
);
console.log(params); // { name: "Alice", age: "25" }