Regular 表达式
一句话解释
regular 表达式 (regex) 是 模式 used 到 match, 搜索, and replace 文本.
用大白话说
regular 表达式 (regex or regexp) 是模式 for matching 文本. 它是 编写之间 slashes (/pattern/flags) or 创建使用 new RegExp(). Regex is used for validation (emails, phone numbers), searching, and replacing text.
Common patterns: \d (digit), \w (word character), \s (whitespace), . (any char), * (zero or more), + (one or more), ? (optional), [] (character set), () (group), | (or).
JavaScript provides 字符串.match, 字符串.replace, 字符串.拆分 (all accept regex), and RegExp.测试 (returns true/false), RegExp.exec (returns match details). Flags include g (global), i (case-insensitive), and m (multiline).
示例
javascript
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test("[email protected]")); // true
console.log(emailRegex.test("not-an-email")); // false
const result = "2024-01-15".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(result[1], result[2], result[3]); // "2024" "01" "15"Regex 模式 能 验证 and extract 部分 的 字符串.
相关术语
相关资源
相关课程
- 数据 类型
学习 关于 regex.
相关工具
- Regex Tester
测试 regular 表达式.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。