正则表达式
约 429 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › 进阶实践 › 正则表达式
创建方式
// 字面量(推荐)
const re1 = /\d+/g;
// 构造函数
const re2 = new RegExp('\\\\d+', 'g');常用方法
const str = 'Hello 123 World 456';
// test:是否匹配
/\d+/.test(str); // true
// exec:返回匹配结果
const re = /(\d+)/g;
let match;
while ((match = re.exec(str)) !== null) {
console.log(match[0]); // "123", "456"
}
// 字符串方法
str.match(/\d+/g); // ["123", "456"]
str.search(/\d+/); // 6(索引)
str.replace(/\d+/g, 'X'); // "Hello X World X"
str.split(/\s+/); // ["Hello", "123", "World", "456"]常用模式
// 字符类
\d // 数字
\w // 字母/数字/下划线
\s // 空白
. // 除换行外的任意字符
[abc] // a/b/c 中的任一个
[^abc]// 除 a/b/c 外的字符
// 量词
* // 0 次或多次
+ // 1 次或多次
? // 0 次或 1 次
{n} // n 次
{n,} // n 次或以上
{n,m} // n 到 m 次
// 分组
(str) // 捕获组
(?:str) // 非捕获组
str1|str2 // 或
// 位置
^ // 开头
$ // 结尾
\b // 单词边界
// 标志
g // 全局
i // 不区分大小写
m // 多行模式实战示例
// 邮箱验证
const email = /^[\w.-]+@[\w.-]+\.\w{2,}$/;
email.test('user@example.com'); // true
// 手机号
const phone = /^1[3-9]\\d{9}$/;
phone.test('13800138000'); // true
// URL
const url = /^https?:\/\/[\w.-]+/;
url.test('https://example.com'); // true
// 用户名(字母开头,4-16位字母或数字)
const username = /^[A-Za-z][A-Za-z0-9_]{3,15}$/;小结
| 方法 | 作用 |
|---|---|
test() | 是否匹配 |
exec() | 匹配结果 |
match() | 字符串上的匹配 |
replace() | 替换 |
split() | 分割 |
