正则表达式是一种用于匹配文本模式的工具。它是由字符和操作符组成的模式,用于搜索、替换和验证字符串。正则表达式在处理文本时非常有用,因为它可以帮助我们有效地匹配和过滤出我们需要的内容。
正则表达式的应用场景非常广泛,例如在以下情况下可以使用正则表达式:
验证用户输入的内容是否符合规范(如电子邮件、电话号码、身份证号码等)。
搜索和替换文本中的特定字符串或模式。
解析和提取文本中的数据,如网页爬虫等。
对文本进行格式化和归一化。
以下是一些常用的正则表达式操作符及其含义:
验证电子邮件地址:
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = "test@example.com";
if (emailRegex.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
提取 URL 中的域名:
const url = "https://www.example.com/path/to/page.html";
const domainRegex = /^https?:\/\/([^/]+)/;
const domain = url.match(domainRegex)[1];
console.log(domain); // 输出:www.example.com
验证手机号码:
const phoneRegex = /^1[3456789]\d{9}$/;
const phone = "13812345678";
if (phoneRegex.test(phone)) {
console.log("Valid phone number");
} else {
console.log("Invalid phone number");
}