Skip to content

C14. 正则表达式初步

4.1. 🌟 正则表达式的基本语法

正则表达式(Regex)是文本匹配的“瑞士军刀”,通过特殊符号组合定义匹配模式。

4.1.1. ⭐ 元字符与基本匹配

符号作用示例匹配结果
.匹配任意单个字符(换行符除外)/a.c/"abc", "a3c"
^匹配字符串开头/^a/"apple" → 匹配
$匹配字符串结尾/p$/"map" → 匹配
*匹配前一个字符 0 次或多次/go*gle/"gogle", "google"
+匹配前一个字符 1 次或多次/go+gle/"google" → 匹配
?匹配前一个字符 0 次或 1 次/colou?r/"color", "colour"

注意

元字符需要转义使用时,需加反斜杠 \/,如匹配 . 字符需写成 \.

4.1.2. 字符集与范围

javascript
// 匹配字母或数字
const regex = /[a-zA-Z0-9]/;

// 范围缩写
/[A-Z]/  // 大写字母
/\d/     // 等价于 [0-9]
/\w/     // 等价于 [A-Za-z0-9_](字母、数字、下划线)

4.1.3. 分组与捕获

javascript
// 捕获组用 () 包裹
const emailRegex = /(\w+)@(\w+)\.com/;
const match = emailRegex.exec("user@example.com");
console.log(match[1]); // user
console.log(match[2]); // example

4.2. ⭐ 正则表达式的修饰符

修饰符(Flags)通过 /.../修饰符 形式附加在正则末尾,改变匹配行为。

修饰符作用示例结果
i忽略大小写/apple/i"Apple" → 匹配
g全局匹配(查找所有匹配)/a/g"banana" → 3次匹配
m多行模式(^/$匹配每行)/^start/m匹配多行开头
例:g修饰符的威力
javascript
const text = "a a a";
const regex = /a/g;
console.log(text.match(regex)); // ["a", "a", "a"]

4.3. 🌟 用 JavaScript 匹配正则表达式

4.3.1. 测试匹配 test() 方法

javascript
const hasNumber = /\d/;
console.log(hasNumber.test("abc123")); // true
console.log(hasNumber.test("hello"));  // false

4.3.2. 获取匹配结果 match()exec()

javascript
// 查找所有邮箱
const emails = "contact@site.com, admin@domain.org";
const regex = /[\w.-]+@[\w.-]+\.[a-z]{2,}/g;
console.log(emails.match(regex)); // ["contact@site.com", "admin@domain.org"]

4.3.3. 多行匹配示例

javascript
const text = "Line1\nLine2";
const regex = /^Line/m; // 多行模式
console.log(text.match(regex)); // ["Line1", "Line2"]

4.4. 🌟 用正则表达式替换字符串

4.4.1. 简单替换 replace()

javascript
const cleaned = "123-456-7890".replace(/-/g, ""); // "1234567890"
const censored = "密码:1234".replace(/\d/g, "*"); // "密码:****"

4.4.2. 使用捕获组引用

javascript
// 将"apple 3" → "apple iii"
const numToLetters = /(apple) (\d)/i;
const result = "Apple 3".replace(numToLetters, "$1 iii"); // "Apple iii"

4.4.3. 动态替换(函数形式)

javascript
// 将所有数字转换为罗马数字
const text = "价格:100";
const regex = /\d+/g;
const result = text.replace(regex, (match) => {
  return romanize(Number(match)); // 假设存在 romanize 函数
});

知识回顾

  1. 基本语法核心
    • 元字符:. * + ? ^ $
    • 字符集:[a-z] \d \w
    • 分组与捕获:(...)$1 参考
  2. 修饰符作用
    • i:忽略大小写
    • g:全局匹配
    • m:多行模式
  3. JavaScript方法
    • test():返回布尔值
    • match()/exec():返回匹配数组
    • replace():字符串替换(支持捕获组)
  4. 陷阱提醒
    • 元字符需要转义(如 .\.
    • g修饰符影响 exec() 行为
    • 捕获组索引从 1 开始

课后练习

  1. (单选)正则表达式 /\d+/g 的作用是?

    • A. 匹配任意字符
    • B. 匹配连续数字
    • C. 匹配单个字母
    • D. 匹配空格
  2. (填空)要匹配以 .com 结尾的邮箱,正则表达式可写为:______。

  3. (代码纠错)修复以下替换代码,将所有大写字母转为小写:

    javascript
    const text = "HELLO";
    const lower = text.replace(/[A-Z]/g, (char) => char.toLowerCase());
    // 错误:未使用捕获组
  4. (操作题)编写正则表达式验证电话号码格式:

    • 格式:138-1234-5678021-2580-1357
    • 要求:区号可选(11位或12位)

备注: (1) 通过替换函数示例展示动态处理能力 (2) 强调多行模式和全局修饰符的实际应用场景 (3) 捕获组与替换中的引用需重点练习

Built by Vitepress | Apache 2.0 Licensed