正则表达式是一种文本匹配的工具,用来匹配符合特定模式的字符串。它可用于数据验证、搜索、分割等多种场合。
字面量字符和字符类
字面量字符直接匹配文本中的字符
字符类使用[]来匹配其中任意一个字符
示例
字面量字符:
const regexLiteral = /hello/;//匹配含有'hello'的字符
console.log(regexLiteral.test("hello world")); // true
console.log(regexLiteral.test("hi there")); // false
字符类用法
const regexCharacterClass = /[aeiou]/;//匹配包含'aeiou'中任意一个的字符
console.log(regexCharacterClass.test("apple")); // true
console.log(regexCharacterClass.test("banana")); // true
元字符
. 匹配出换行符意外的任意一个字符
const regexDot = /a.b/;//
console.log(regexDot.test("acb")); // true
console.log(regexDot.test("a\nb")); // false
^ 匹配字符串的开始
$ 匹配字符串的结束
const regexStartEnd = /^hello$/;//匹配'hello',多一点少一点都不行
console.log(regexStartEnd.test("hello")); // true
console.log(regexStartEnd.test("hello!")); // false
console.log(regexStartEnd.test("hi hello")); // false
\d 匹配任意数字相当于[0-9]
\w 匹配任意字符、数字、下划线 相当于[a-zA-Z0-9]
\s 匹配任意空白字符
量词
用于指定匹配次数,包括{n} 表示匹配恰好n次、{n,}表示至少匹配n次、{n,m}表示匹配次数在n和m之间
a{3}匹配连续出现3次的字符'a'
\d{2,4} 匹配出现2到4次的数字
const regexQuantifier = /\d{3}/;//匹配至少连续出现三次数字的字符
console.log(regexQuantifier.test("123")); // true
console.log(regexQuantifier.test("4567")); // true
console.log(regexQuantifier.test("12")); // false
分组
使用()表示一个组,可以对组内的内容进行分组和捕获
捕获日期忠的年月日
const regexGroup=(\d{4})-(\d{2})-(\d{2})
const date=2025-03-02
const match=date.match(regexGroup)
match[1] 2025
match[2] 03
match[3] 02
分组而不进行捕获
(?:...)
const text = "apple banana cherry";
const regexNonCapturingGroup = /(?:apple|banana) (\w+)/;
const match = text.match(regexNonCapturingGroup);
console.log(match); // 匹配结果数组
console.log(match[1]); // "cherry"
反向引用
可以使用反向引用\1,\2等来引用之前捕获的分组,使得可以匹配重复出现的内容
const regexBackreference = /(\w+)\s\1/;
console.log(regexBackreference.test("hello hello")); // true
console.log(regexBackreference.test("hi there")); // false
实际项目中使用正则表达式
1、邮箱验证
const emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b/;
const isValidEmail = emailPattern.test("user@example.com");
2.提取日期信息
const datePattern = /(\d{4})-(\d{2})-(\d{2})/;
const text = "今天是2022-01-16,明天是2022-01-17。";
const matches = text.matchAll(datePattern);
3.替换文本中的URL
const urlPattern = /https?://\S+/;
const text = "请访问我的博客:https://www.example.com。";
const modifiedText = text.replace(urlPattern, "[链接]");