⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

JS 正则表达式

学习 RegExp 进行模式匹配 · 难度:高级 · +15XP

JavaScript 正则表达式完全指南

正则表达式(Regular Expression,简称 RegEx)是用于匹配、查找、提取和替换字符串中特定模式的强大工具。JavaScript 内置正则表达式引擎,通过 RegExp 构造函数或字面量 /pattern/flags 创建,广泛用于表单验证、数据提取、文本处理等场景。

创建正则表达式

  1. 字面量方式:/pattern/flags
  2. 构造函数方式:new RegExp("pattern", "flags")
  3. 常用标志:g 全局、i 忽略大小写、m 多行、s dotAll、u Unicode
// 两种创建方式
const re1 = /hello/i;                      // 字面量
const re2 = new RegExp("hello", "i");      // 构造函数

// 常用标志 const re = /pattern/gimsuy; // g: global 全局匹配 // i: ignoreCase 忽略大小写 // m: multiline 多行模式 // s: dotAll 使 . 匹配换行符 // u: unicode Unicode 模式 // y: sticky 粘性匹配

正则表达式核心方法

方法说明返回值
re.test(str)测试是否匹配true / false
re.exec(str)执行匹配(含捕获组)Arraynull
str.match(re)查找匹配项Arraynull
str.matchAll(re)查找所有匹配(迭代器)Iterator
str.replace(re, sub)替换匹配项新字符串
str.search(re)查找位置索引数字(索引或 -1)
str.split(re)按正则分割字符串数组

常用正则表达式与实战

// 表单验证常用正则
const patterns = {
  email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/,
  phone: /^1[3-9]d{9}$/,
  url: /^https?://[w.-]+(?:.[w.-]+)+[w-._~:/?#[]@!$&'()*+,;=]+$/,
  zip: /^d{6}$/,
  idCard: /^[1-9]d{5}(18|19|20)d{2}(0[1-9]|1[0-2])(0[1-9]|[12]d|3[01])d{3}[dXx]$/
};

// 测试示例 const email = "user@example.com"; console.log(patterns.email.test(email)); // true

// 提取所有数字 const text = "价格:¥128.50,数量:3,总计:¥385.50"; const numbers = text.match(/d+/g); console.log(numbers); // ["128", "50", "3", "385", "50"]

// 使用捕获组提取信息 const dateStr = "2026-05-30"; const dateRe = /(d{4})-(d{2})-(d{2})/; const [, year, month, day] = dateStr.match(dateRe); console.log(year, month, day); // "2026", "05", "30"

// 高级替换:使用捕获组 const name = "Doe, John"; const swapped = name.replace(/(w+),s*(w+)/, "$2 $1"); console.log(swapped); // "John Doe"

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0