正则表达式 and
正则表达式(Regular Expression)简称正则,是一种表达文本的特殊符号表示方法。正则通常由字符、限定符、括号等要素组成,能够用于快速的匹配、查找、替换、提取文本等操作。在开发中,正则表达式被广泛应用于数据校验、搜索语法、字符串处理等场景中,甚至成为程序员必备的基本技能之一。
正则表达式语法
正则表达式语法是庞杂而实用的。通常包含以下几种基本元素:
- 普通字符:标识自身字符,如
/hello/
表示匹配含有字符串 “hello” 的文本; - 限定符:控制前面字符的出现次数,如
*
表示匹配前一个字符0次到多次; - 转义字符:用反斜杠
\
将特殊字符转义为普通字符,如\d
表示匹配数字等特殊字符; - 按照量词匹配:分别是 “?” 匹配 0 次或 1 次、”+” 匹配 1 次或多次、”{}” 限定符表示匹配一个特定区间的次数;
- 字符集合:用方括号 [] 匹配包含单个字符的任何集合或范围;
- 捕获组:用括号 () 捕获匹配的文本,捕获的文本内容可以在表达式后续的处理流程中使用;
下面是一些常见的正则表达式语法示例:
匹配任意字符 .
const str = 'abc123';
const regx = /a./;
console.log(regx.test(str)); // true
匹配数字 \d
const str = 'abc123';
const regx = /\d/;
console.log(regx.test(str)); // true
匹配非数字 \D
const str = 'abc123';
const regx = /\D/;
console.log(regx.test(str)); // true
匹配字母 [a-z]
const str = 'abc123';
const regx = /[a-z]/;
console.log(regx.test(str)); // true
匹配字母和数字 [a-zA-Z0-9]
const str = 'abc123';
const regx = /[a-zA-Z0-9]/;
console.log(regx.test(str)); // true
匹配空白字符 \s
const str = 'abc 123';
const regx = /\s/;
console.log(regx.test(str)); // true
匹配非空白字符 \s
const str = 'abc 123';
const regx = /\S/;
console.log(regx.test(str)); // true
实战应用
数据校验
正则表达式在数据校验中十分常用。比如,我们可以使用正则表达式校验输入的手机号码是否符合规范。
function checkMobile(mobile) {
const regx = /^1[3-9]\d{9}$/;
return regx.test(mobile);
}
console.log(checkMobile('13512345678')); // true
console.log(checkMobile('12345678901')); // false
通过以上代码,我们可以看到,我们使用了正则表达式校验输入的手机号码是否符合规范。这个正则表达式的含义就是以1开头,第二个字符是3~9的任意数字,后面跟9个任意数字。
搜索语法
正则表达式能够用于字符串的搜索操作。比如,我们可以使用正则表达式匹配以 “https://” 和 “http://” 开头,以 “.com” 或 “.cn” 结尾的链接。
const str = '请访问以下网站:http://www.baidu.com https://www.google.com http://www.aliyun.cn';
const regx = /(https?:\/\/\S+\.(com|cn))/g;
console.log(str.match(regx));
// ["http://www.baidu.com", "https://www.google.com", "http://www.aliyun.cn"]
通过以上代码,我们可以看到,我们使用了正则表达式匹配输入文本中的链接。这个正则表达式的含义就是以 “https://” 或 “http://” 开头,接下来是一些非空白字符,最后是 “.com” 或 “.cn”。
字符串处理
除了数据校验和搜索语法,正则表达式还能够用于字符串的处理。比如,我们可以使用正则表达式替换掉字符串中的某些字符。
const str = '今天是2021年1月1日,过去的是2020年,未来的是2022年';
const regx = /(\d{4})年/g;
const newStr = str.replace(regx, '$1-');
console.log(newStr);
// "今天是2021年1月1日,过去的是2020-年,未来的是2022-年"
通过以上代码,我们可以看到,我们使用了正则表达式将字符串中的 “年” 替换成了 “-年”,这个正则表达式的含义就是匹配四位数字加上 “年” 的组合,然后用分组引用的形式替换成了 “1-“,其中 “1″ 表示匹配的第一个分组(也就是四位数字)。
常用正则表达式
下面介绍一些常见的常用正则表达式:
匹配邮箱
const regx = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
匹配身份证号码
const regx = /(^\d{15})|(^\d{18})|(^\d{17}(\d|X|x)$)/;
匹配中文字符
const regx = /[\u4e00-\u9fa5]+/;
匹配 IP 地址
const regx = /^((([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]))$/;
匹配 URL
const regx = /[a-zA-z]+:\/\/[^\s]*/;
结论
正则表达式是一种十分强大的文本处理工具。在日常开发中,我们可根据实际情况灵活应用正则表达式,能够大大提高我们代码的效率。同时,由于正则表达式的语法较为复杂,我们需要持续练习,不断积累经验。