Appearance
JavaScript 正则表达式
什么是正则表达式
正则表达式(Regular Expression,简称 regex 或 regexp)是一种用于匹配字符串中字符组合的模式。在 JavaScript 中,正则表达式是对象,用于描述字符模式。
正则表达式可以用于:
- 搜索字符串
- 替换字符串
- 提取字符串
- 验证字符串格式
正则表达式的创建
1. 字面量语法
使用斜杠 / 包围正则表达式模式。
javascript
// 字面量语法
const regex = /pattern/flags;
// 示例
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
const phoneRegex = /^1[3-9]\d{9}$/;2. 构造函数语法
使用 RegExp 构造函数创建正则表达式。
javascript
// 构造函数语法
const regex = new RegExp("pattern", "flags");
// 示例
const emailRegex = new RegExp("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
const phoneRegex = new RegExp("^1[3-9]\\d{9}$");
// 动态创建正则表达式
const pattern = "hello";
const regex = new RegExp(pattern, "gi");正则表达式的标志
标志(Flags)用于控制正则表达式的行为。
| 标志 | 描述 |
|---|---|
g | 全局匹配 - 查找所有匹配项 |
i | 忽略大小写 |
m | 多行匹配 - ^ 和 $ 匹配每行的开始和结束 |
s | 允许 . 匹配换行符 |
u | Unicode 模式 - 正确处理 Unicode 字符 |
y | 粘性匹配 - 从目标字符串的当前位置开始匹配 |
javascript
// 示例
// 全局匹配
const regex1 = /a/g;
const str1 = "abcabc";
console.log(str1.match(regex1)); // ['a', 'a']
// 忽略大小写
const regex2 = /a/i;
const str2 = "Abc";
console.log(str2.match(regex2)); // ['A']
// 多行匹配
const regex3 = /^a/m;
const str3 = "abc\nab";
console.log(str3.match(regex3)); // ['a'](匹配第一行的开始)
// Unicode 模式
const regex4 = /\u{1F600}/u;
const str4 = "😄";
console.log(str4.match(regex4)); // ['😄']正则表达式的基本语法
1. 字符类
字符类用于匹配指定范围内的字符。
| 字符 | 描述 |
|---|---|
[abc] | 匹配方括号内的任意一个字符 |
[^abc] | 匹配除了方括号内的任意一个字符 |
[a-z] | 匹配 a 到 z 之间的任意一个字符 |
[A-Z] | 匹配 A 到 Z 之间的任意一个字符 |
[0-9] | 匹配 0 到 9 之间的任意一个数字 |
[a-zA-Z0-9] | 匹配字母和数字 |
javascript
// 示例
const regex1 = /[abc]/;
console.log(regex1.test("a")); // true
console.log(regex1.test("d")); // false
const regex2 = /[^abc]/;
console.log(regex2.test("a")); // false
console.log(regex2.test("d")); // true
const regex3 = /[a-z]/;
console.log(regex3.test("A")); // false
console.log(regex3.test("a")); // true
const regex4 = /[0-9]/;
console.log(regex4.test("5")); // true
console.log(regex4.test("a")); // false2. 元字符
元字符是具有特殊含义的字符。
| 元字符 | 描述 |
|---|---|
. | 匹配任意单个字符(除了换行符,除非使用 s 标志) |
^ | 匹配字符串的开始 |
$ | 匹配字符串的结束 |
* | 匹配前面的表达式 0 次或多次 |
+ | 匹配前面的表达式 1 次或多次 |
? | 匹配前面的表达式 0 次或 1 次 |
\d | 匹配任意数字,等价于 [0-9] |
\D | 匹配任意非数字,等价于 [^0-9] |
\w | 匹配任意字母、数字或下划线,等价于 [a-zA-Z0-9_] |
\W | 匹配任意非字母、数字或下划线,等价于 [^a-zA-Z0-9_] |
\s | 匹配任意空白字符(空格、制表符、换行符等) |
\S | 匹配任意非空白字符 |
\b | 匹配单词边界 |
\B | 匹配非单词边界 |
javascript
// 示例
const regex1 = /./;
console.log(regex1.test("a")); // true
console.log(regex1.test("\n")); // false(默认情况下不匹配换行符)
const regex2 = /^a/;
console.log(regex2.test("abc")); // true
console.log(regex2.test("bac")); // false
const regex3 = /a$/;
console.log(regex3.test("abc")); // false
console.log(regex3.test("cba")); // true
const regex4 = /a*/;
console.log("".match(regex4)); // ['']
console.log("a".match(regex4)); // ['a']
console.log("aaa".match(regex4)); // ['aaa']
const regex5 = /a+/;
console.log("".match(regex5)); // null
console.log("a".match(regex5)); // ['a']
console.log("aaa".match(regex5)); // ['aaa']
const regex6 = /a?/;
console.log("".match(regex6)); // ['']
console.log("a".match(regex6)); // ['a']
console.log("aaa".match(regex6)); // ['a']
const regex7 = /\d/;
console.log(regex7.test("5")); // true
console.log(regex7.test("a")); // false
const regex8 = /\w/;
console.log(regex8.test("a")); // true
console.log(regex8.test("5")); // true
console.log(regex8.test("_")); // true
console.log(regex8.test("@")); // false
const regex9 = /\s/;
console.log(regex9.test(" ")); // true
console.log(regex9.test("\t")); // true
console.log(regex9.test("a")); // false
const regex10 = /\bword\b/;
console.log(regex10.test("word")); // true
console.log(regex10.test("password")); // false
console.log(regex10.test("word123")); // false3. 量词
量词用于指定匹配的次数。
| 量词 | 描述 |
|---|---|
* | 匹配前面的表达式 0 次或多次,等价于 {0,} |
+ | 匹配前面的表达式 1 次或多次,等价于 {1,} |
? | 匹配前面的表达式 0 次或 1 次,等价于 {0,1} |
{n} | 匹配前面的表达式恰好 n 次 |
{n,} | 匹配前面的表达式至少 n 次 |
{n,m} | 匹配前面的表达式至少 n 次,最多 m 次 |
javascript
// 示例
const regex1 = /a{3}/;
console.log(regex1.test("a")); // false
console.log(regex1.test("aaa")); // true
console.log(regex1.test("aaaa")); // true(匹配前三个 a)
const regex2 = /a{2,}/;
console.log(regex2.test("a")); // false
console.log(regex2.test("aa")); // true
console.log(regex2.test("aaa")); // true
const regex3 = /a{1,3}/;
console.log(regex3.test("a")); // true
console.log(regex3.test("aaa")); // true
console.log(regex3.test("aaaa")); // true(匹配前三个 a)
const regex4 = /\d{4}/;
console.log(regex4.test("123")); // false
console.log(regex4.test("1234")); // true
console.log(regex4.test("12345")); // true(匹配前四个数字)4. 分组和捕获
使用括号 () 进行分组和捕获。
javascript
// 示例
// 分组
const regex1 = /(ab)+/;
console.log(regex1.test("ab")); // true
console.log(regex1.test("abab")); // true
console.log(regex1.test("aab")); // false
// 捕获
const regex2 = /(\d{4})-(\d{2})-(\d{2})/;
const date = "2023-12-01";
const match = date.match(regex2);
console.log(match); // ['2023-12-01', '2023', '12', '01']
console.log(match[0]); // 完整匹配
console.log(match[1]); // 第一个捕获组
console.log(match[2]); // 第二个捕获组
console.log(match[3]); // 第三个捕获组
// 非捕获组(使用 ?:)
const regex3 = /(?:\d{4})-(\d{2})-(\d{2})/;
const match3 = date.match(regex3);
console.log(match3); // ['2023-12-01', '12', '01'](只有两个捕获组)5. 选择(或)
使用 | 表示选择(或)。
javascript
// 示例
const regex = /apple|banana|orange/;
console.log(regex.test("apple")); // true
console.log(regex.test("banana")); // true
console.log(regex.test("orange")); // true
console.log(regex.test("grape")); // false
// 结合分组
const regex2 = /(apple|banana|orange) juice/;
console.log(regex2.test("apple juice")); // true
console.log(regex2.test("banana juice")); // true
console.log(regex2.test("orange juice")); // true
console.log(regex2.test("grape juice")); // false6. 转义字符
使用 \ 转义特殊字符,使其成为普通字符。
javascript
// 示例
// 匹配点号(.)
const regex1 = /\./;
console.log(regex1.test("a.b")); // true
console.log(regex1.test("ab")); // false
// 匹配星号(*)
const regex2 = /\*/;
console.log(regex2.test("a*b")); // true
console.log(regex2.test("ab")); // false
// 匹配括号(())
const regex3 = /\(\)/;
console.log(regex3.test("()")); // true
console.log(regex3.test("ab")); // false
// 匹配反斜杠(\)
const regex4 = /\\/;
console.log(regex4.test("a\b")); // true
console.log(regex4.test("ab")); // false7. 断言
断言(Assertions)用于指定匹配的位置,而不是匹配字符本身。
| 断言 | 描述 |
|---|---|
x(?=y) | 正向先行断言 - 匹配 x 仅当 x 后面跟着 y |
x(?!y) | 负向先行断言 - 匹配 x 仅当 x 后面不跟着 y |
(?<=y)x | 正向后行断言 - 匹配 x 仅当 x 前面是 y |
(?<!y)x | 负向后行断言 - 匹配 x 仅当 x 前面不是 y |
javascript
// 示例
// 正向先行断言
const regex1 = /x(?=y)/;
console.log("xy".match(regex1)); // ['x'](匹配 x 后面跟着 y)
console.log("xz".match(regex1)); // null(x 后面不是 y)
// 负向先行断言
const regex2 = /x(?!y)/;
console.log("xz".match(regex2)); // ['x'](匹配 x 后面不是 y)
console.log("xy".match(regex2)); // null(x 后面是 y)
// 正向后行断言
const regex3 = /(?<=y)x/;
console.log("yx".match(regex3)); // ['x'](匹配 x 前面是 y)
console.log("zx".match(regex3)); // null(x 前面不是 y)
// 负向后行断言
const regex4 = /(?<!y)x/;
console.log("zx".match(regex4)); // ['x'](匹配 x 前面不是 y)
console.log("yx".match(regex4)); // null(x 前面是 y)
// 应用示例:提取价格
const regex5 = /(?<=\$)\d+(\.\d{2})?/;
const price = "$19.99";
console.log(price.match(regex5)); // ['19.99', '.99']
// 应用示例:验证密码强度(至少 8 位,包含大小写字母和数字)
const regex6 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(regex6.test("Password123")); // true
console.log(regex6.test("password123")); // false(缺少大写字母)
console.log(regex6.test("PASSWORD123")); // false(缺少小写字母)
console.log(regex6.test("Password")); // false(缺少数字)
console.log(regex6.test("Pass123")); // false(长度不足)正则表达式的方法
1. 字符串方法
match()
返回匹配的结果数组,或 null(如果没有匹配)。
javascript
// 示例
const str = "abcabc";
const regex = /a/g;
console.log(str.match(regex)); // ['a', 'a']
// 带捕获组
const str2 = "2023-12-01";
const regex2 = /(\d{4})-(\d{2})-(\d{2})/;
console.log(str2.match(regex2)); // ['2023-12-01', '2023', '12', '01']
// 全局匹配下,捕获组不会被返回
const regex3 = /(\d{4})-(\d{2})-(\d{2})/g;
console.log(str2.match(regex3)); // ['2023-12-01']matchAll()
返回一个迭代器,包含所有匹配项(包括捕获组)。
javascript
// 示例
const str = "2023-12-01 2023-12-02";
const regex = /(\d{4})-(\d{2})-(\d{2})/g;
const matches = str.matchAll(regex);
// 转换为数组
const matchArray = [...matches];
console.log(matchArray);
// [
// ['2023-12-01', '2023', '12', '01'],
// ['2023-12-02', '2023', '12', '02']
// ]
// 遍历迭代器
for (const match of matches) {
console.log(match[0]); // 完整匹配
console.log(match[1]); // 年
console.log(match[2]); // 月
console.log(match[3]); // 日
}search()
返回第一个匹配项的索引,或 -1(如果没有匹配)。
javascript
// 示例
const str = "abcabc";
const regex = /a/;
console.log(str.search(regex)); // 0
const regex2 = /z/;
console.log(str.search(regex2)); // -1replace()
替换匹配的部分,并返回新字符串。
javascript
// 示例
const str = "abcabc";
const regex = /a/;
console.log(str.replace(regex, "x")); // 'xbcabc'(只替换第一个匹配)
const regex2 = /a/g;
console.log(str.replace(regex2, "x")); // 'xbcxbc'(替换所有匹配)
// 使用回调函数
const str2 = "2023-12-01";
const regex3 = /(\d{4})-(\d{2})-(\d{2})/;
const result = str2.replace(regex3, "$2/$3/$1");
console.log(result); // '12/01/2023'
// 回调函数参数:完整匹配, 捕获组1, 捕获组2, ..., 索引, 原字符串
const result2 = str2.replace(regex3, (match, year, month, day) => {
return `${month}/${day}/${year}`;
});
console.log(result2); // '12/01/2023'
// 应用示例:首字母大写
const str3 = "hello world";
const regex4 = /\b\w/g;
const result3 = str3.replace(regex4, (match) => {
return match.toUpperCase();
});
console.log(result3); // 'Hello World'split()
根据正则表达式分割字符串,返回数组。
javascript
// 示例
const str = "a,b,c";
const regex = /,/;
console.log(str.split(regex)); // ['a', 'b', 'c']
// 使用正则表达式分割多个分隔符
const str2 = "a,b;c.d";
const regex2 = /[,;.]/;
console.log(str2.split(regex2)); // ['a', 'b', 'c', 'd']
// 分割空白字符
const str3 = "a b\tc\nd";
const regex3 = /\s/;
console.log(str3.split(regex3)); // ['a', 'b', 'c', 'd']
// 限制分割次数
const str4 = "a,b,c,d";
const regex4 = /,/;
console.log(str4.split(regex4, 2)); // ['a', 'b']2. 正则表达式方法
test()
测试字符串是否匹配正则表达式,返回 true 或 false。
javascript
// 示例
const regex = /a/;
console.log(regex.test("abc")); // true
console.log(regex.test("bc")); // false
// 全局匹配时的注意事项
const regex2 = /a/g;
const str = "abcabc";
console.log(regex2.test(str)); // true
console.log(regex2.test(str)); // true
console.log(regex2.test(str)); // false(因为 lastIndex 已经到达字符串末尾)
console.log(regex2.test(str)); // true(lastIndex 重置为 0)
// 重置 lastIndex
regex2.lastIndex = 0;
console.log(regex2.test(str)); // trueexec()
执行正则表达式匹配,返回匹配结果数组,或 null(如果没有匹配)。
javascript
// 示例
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const str = "2023-12-01";
const match = regex.exec(str);
console.log(match); // ['2023-12-01', '2023', '12', '01']
// 全局匹配
const regex2 = /a/g;
const str2 = "abcabc";
let match2;
while ((match2 = regex2.exec(str2)) !== null) {
console.log(`匹配: ${match2[0]}, 索引: ${match2.index}`);
// 匹配: a, 索引: 0
// 匹配: a, 索引: 3
}正则表达式的应用场景
1. 表单验证
javascript
// 表单验证
// 验证邮箱
function validateEmail(email) {
const regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
return regex.test(email);
}
// 验证手机号
function validatePhone(phone) {
const regex = /^1[3-9]\d{9}$/;
return regex.test(phone);
}
// 验证密码强度
function validatePassword(password) {
// 至少 8 位,包含大小写字母和数字
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
return regex.test(password);
}
// 验证 URL
function validateUrl(url) {
const regex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
return regex.test(url);
}
// 验证身份证号
function validateIdCard(idCard) {
const regex =
/^[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]$/;
return regex.test(idCard);
}
// 使用示例
console.log(validateEmail("john@example.com")); // true
console.log(validatePhone("13812345678")); // true
console.log(validatePassword("Password123")); // true
console.log(validateUrl("https://www.example.com")); // true
console.log(validateIdCard("110101199001011234")); // true2. 数据提取
javascript
// 数据提取
// 提取日期
function extractDate(str) {
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const match = str.match(regex);
if (match) {
return {
year: match[1],
month: match[2],
day: match[3],
};
}
return null;
}
// 提取数字
function extractNumbers(str) {
const regex = /\d+/g;
return str.match(regex) || [];
}
// 提取 HTML 标签
function extractTags(html) {
const regex = /<([a-z][a-z0-9]*)[^>]*>/gi;
const matches = html.match(regex) || [];
return matches.map((match) => {
const tagMatch = match.match(/<([a-z][a-z0-9]*)[^>]*>/i);
return tagMatch ? tagMatch[1] : "";
});
}
// 提取 URL 参数
function extractUrlParams(url) {
const params = {};
const regex = /[?&]([^=#]+)=([^&#]*)/g;
let match;
while ((match = regex.exec(url)) !== null) {
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
}
return params;
}
// 使用示例
console.log(extractDate("Today is 2023-12-01")); // { year: '2023', month: '12', day: '01' }
console.log(extractNumbers("The price is $19.99 for 3 items")); // ['19', '99', '3']
console.log(extractTags("<div><p>Hello</p></div>")); // ['div', 'p']
console.log(extractUrlParams("https://www.example.com?name=John&age=30")); // { name: 'John', age: '30' }3. 字符串替换
javascript
// 字符串替换
// 替换所有空白字符为单个空格
function normalizeWhitespace(str) {
return str.replace(/\s+/g, " ").trim();
}
// 移除 HTML 标签
function removeHtmlTags(html) {
return html.replace(/<[^>]*>/g, "");
}
// 格式化日期
function formatDate(dateStr) {
return dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
}
// 敏感信息脱敏
function maskSensitiveInfo(str) {
// 手机号脱敏
str = str.replace(/1([3-9])\d{4}(\d{4})/g, "1$1****$2");
// 邮箱脱敏
str = str.replace(/(\w{1,3})@(\w+\.\w+)/g, "$1***@$2");
return str;
}
// 驼峰命名转连字符命名
function camelToKebab(str) {
return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase();
}
// 连字符命名转驼峰命名
function kebabToCamel(str) {
return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
}
// 使用示例
console.log(normalizeWhitespace("Hello world\n\tfoo")); // 'Hello world foo'
console.log(removeHtmlTags("<div>Hello <b>world</b></div>")); // 'Hello world'
console.log(formatDate("2023-12-01")); // '12/01/2023'
console.log(maskSensitiveInfo("Phone: 13812345678, Email: john@example.com")); // 'Phone: 138****5678, Email: joh***@example.com'
console.log(camelToKebab("camelCase")); // 'camel-case'
console.log(kebabToCamel("kebab-case")); // 'kebabCase'4. 文本搜索
javascript
// 文本搜索
// 搜索单词
function searchWord(text, word) {
const regex = new RegExp(`\\b${word}\\b`, "gi");
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push({
word: match[0],
index: match.index,
});
}
return matches;
}
// 查找重复单词
function findDuplicateWords(text) {
const regex = /\b(\w+)\s+\1\b/gi;
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push(match[0]);
}
return matches;
}
// 查找所有邮箱
function findEmails(text) {
const regex = /[\w-\.]+@([\w-]+\.)+[\w-]{2,4}/g;
return text.match(regex) || [];
}
// 使用示例
const text =
"Hello world, hello John. Email: john@example.com, admin@example.com";
console.log(searchWord(text, "hello")); // [{ word: 'Hello', index: 0 }, { word: 'hello', index: 13 }]
console.log(findDuplicateWords("Hello hello world world")); // ['Hello hello', 'world world']
console.log(findEmails(text)); // ['john@example.com', 'admin@example.com']正则表达式的最佳实践
1. 性能优化
- 使用具体的模式:避免使用过于宽泛的模式,如
.* - 使用量词的贪婪与非贪婪:根据需要选择合适的量词(
*贪婪,*?非贪婪) - 使用预编译的正则表达式:对于重复使用的正则表达式,使用字面量语法或预编译
- 避免回溯:复杂的正则表达式可能导致回溯,影响性能
javascript
// 好的做法:具体的模式
const regex1 = /^\d{4}$/; // 匹配 4 位数字
// 不好的做法:宽泛的模式
const regex2 = /.*\d{4}.*/; // 过于宽泛
// 贪婪与非贪婪
const str = "<div>hello</div><div>world</div>";
const regex3 = /<div>.*<\/div>/; // 贪婪,匹配整个字符串
console.log(str.match(regex3)[0]); // '<div>hello</div><div>world</div>'
const regex4 = /<div>.*?<\/div>/; // 非贪婪,匹配第一个 <div>
console.log(str.match(regex4)[0]); // '<div>hello</div>'
// 预编译正则表达式
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
function validateEmails(emails) {
return emails.filter((email) => emailRegex.test(email));
}2. 可读性
- 使用注释:对于复杂的正则表达式,添加注释
- 使用命名捕获组:提高代码的可读性
- 拆分复杂的正则表达式:将复杂的正则表达式拆分为多个部分
javascript
// 命名捕获组
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const str = "2023-12-01";
const match = str.match(regex);
console.log(match.groups); // { year: '2023', month: '12', day: '01' }
console.log(match.groups.year); // '2023'
// 拆分复杂的正则表达式
const emailPattern = [
"^[\\w-\\.]+", // 用户名
"@",
"([\\w-]+\\.)+", // 域名
"[\\w-]{2,4}", // 顶级域名
"$",
].join("");
const emailRegex = new RegExp(emailPattern);3. 边界情况
- 空字符串:考虑空字符串的情况
- 特殊字符:处理特殊字符的转义
- Unicode 字符:使用
u标志处理 Unicode 字符 - 多行文本:使用
m标志处理多行文本
javascript
// 处理空字符串
function validateInput(input) {
if (!input) return false;
const regex = /^\d+$/;
return regex.test(input);
}
// 转义特殊字符
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// 处理 Unicode 字符
const regex = /^\p{L}+$/u; // 匹配任意 Unicode 字母
console.log(regex.test("Hello")); // true
console.log(regex.test("你好")); // true
// 处理多行文本
const regex2 = /^\d+/m; // 匹配每行的开始的数字
const text = "123\n456\n789";
console.log(text.match(regex2)); // ['123']4. 测试
- 编写测试用例:为正则表达式编写测试用例
- 使用在线工具:使用在线正则表达式测试工具验证正则表达式
javascript
// 测试用例
function testRegex(regex, testCases) {
testCases.forEach((testCase) => {
const result = regex.test(testCase.input);
console.log(`${testCase.input}: ${result} (期望: ${testCase.expected})`);
});
}
// 测试邮箱正则表达式
const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
const testCases = [
{ input: "john@example.com", expected: true },
{ input: "john.doe@example.com", expected: true },
{ input: "john@example.co.uk", expected: true },
{ input: "john@", expected: false },
{ input: "@example.com", expected: false },
{ input: "john@.com", expected: false },
];
testRegex(emailRegex, testCases);正则表达式的工具
1. 在线测试工具
2. 正则表达式生成器
- Regex Generator - 根据示例生成正则表达式
- Regular Expressions 101 - 也可以生成正则表达式
3. 常用正则表达式库
- validator.js - 字符串验证库
- xregexp - 扩展的正则表达式库
总结
正则表达式是 JavaScript 中强大的工具,用于匹配、搜索、替换和验证字符串。它具有以下特点:
- 灵活的语法:支持字符类、元字符、量词、分组、断言等多种语法
- 多种方法:可以使用字符串方法(如
match()、replace())和正则表达式方法(如test()、exec()) - 广泛的应用:用于表单验证、数据提取、字符串替换、文本搜索等场景
- 性能考虑:复杂的正则表达式可能影响性能,需要注意优化
- 可读性:复杂的正则表达式可能难以理解,需要注意代码的可读性
通过掌握正则表达式的基本语法和应用技巧,我们可以更有效地处理字符串操作,提高代码的质量和效率。