4、正则表达式实用示例
2025/9/23大约 2 分钟
正则表达式实用示例
正则表达式在实际开发中有着广泛的应用。本文将介绍一些常见的实用正则表达式示例,帮助你更好地理解和应用正则表达式。
1. 表单验证
电子邮件验证
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
console.log(emailRegex.test('user@example.com')); // true
console.log(emailRegex.test('invalid-email@')); // false
密码强度验证
至少8个字符,包含至少一个大写字母,一个小写字母和一个数字:
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
console.log(passwordRegex.test('Passw0rd')); // true
console.log(passwordRegex.test('password')); // false
手机号码验证(中国大陆)
const phoneRegex = /^1[3-9]\d{9}$/;
console.log(phoneRegex.test('13812345678')); // true
console.log(phoneRegex.test('12345678901')); // false
2. 数据提取
从 URL 中提取参数
const url = 'https://example.com/search?query=regex&page=1';
const regex = /[?&]([^=&]+)=([^&]*)/g;
let match;
const params = {};
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
console.log(params); // { query: 'regex', page: '1' }
提取 HTML 标签内容
const html = '<div><p>段落内容</p><span>span内容</span></div>';
const regex = /<p>(.*?)<\/p>/g;
const paragraphs = html.match(regex);
console.log(paragraphs); // ['<p>段落内容</p>']
3. 字符串操作
将驼峰命名转换为短横线命名
const camelCase = 'backgroundColor';
const kebabCase = camelCase.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
console.log(kebabCase); // 'background-color'
格式化数字(添加千位分隔符)
const number = 1234567.89;
const formatted = number.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
console.log(formatted); // '1,234,567.89'
4. 代码分析
提取 JavaScript 中的注释
const code = `
// 这是单行注释
function example() {
/* 这是
多行注释 */
return true;
};
`;
const singleLineComments = code.match(/\/\/.*$/gm);
const multiLineComments = code.match(/\/\*[\s\S]*?\*\//g);
console.log(singleLineComments); // ['// 这是单行注释']
console.log(multiLineComments); // ['/* 这是\n 多行注释 */']
通过这些实用示例,你可以看到正则表达式在实际编程中的强大功能。在下一篇文章中,我们将深入探讨正则表达式的性能优化技巧。