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 函数
});
知识回顾
- 基本语法核心:
- 元字符:
.
*
+
?
^
$
- 字符集:
[a-z]
\d
\w
- 分组与捕获:
(...)
和$1
参考
- 元字符:
- 修饰符作用:
i
:忽略大小写g
:全局匹配m
:多行模式
- JavaScript方法:
test()
:返回布尔值match()
/exec()
:返回匹配数组replace()
:字符串替换(支持捕获组)
- 陷阱提醒:
- 元字符需要转义(如
.
→\.
) g
修饰符影响exec()
行为- 捕获组索引从
1
开始
- 元字符需要转义(如
课后练习
(单选)正则表达式
/\d+/g
的作用是?- A. 匹配任意字符
- B. 匹配连续数字
- C. 匹配单个字母
- D. 匹配空格
(填空)要匹配以
.com
结尾的邮箱,正则表达式可写为:______。(代码纠错)修复以下替换代码,将所有大写字母转为小写:
javascriptconst text = "HELLO"; const lower = text.replace(/[A-Z]/g, (char) => char.toLowerCase()); // 错误:未使用捕获组
(操作题)编写正则表达式验证电话号码格式:
- 格式:
138-1234-5678
或021-2580-1357
- 要求:区号可选(11位或12位)
- 格式:
备注: (1) 通过替换函数示例展示动态处理能力 (2) 强调多行模式和全局修饰符的实际应用场景 (3) 捕获组与替换中的引用需重点练习