前端星
1. 正则表达式的创建和使用
1.1 创建正则表达式
-
使用正则表达式字面量
const reg = /[a-z]\d+[a-z]/i;
/ /
表示将正则表达式内容包括进来,[a-z]
表示字母,\d
表示数字,+
表示前面的(\d
)重复一次或多次,i
表示修饰符,正则表达式忽略大小写- 优点:简单方便和不需要考虑二次转义
- 缺点:子内容无法重复使用、过长的正则导致可读性差
-
使用 RegExp 构造函数
const alphabet = '[a-z]'; const reg = new RegExp(`${alphabet}\\d+${alphabet}`, 'i');
- 优点:子内容可以重复使用、可以通过控制子内容的粒度提高可读性
- 缺点:二次转义的问题非常容易导致 bug
const reg = new RegExp(`\d+`); reg.test('1'); // false reg.test('ddd'); // true
1.2 使用正则表达式
-
RegExp.prototype.test()
const reg = /[a-z]\d+[a-z]/i; reg.test('a1a'); // true reg.test('1a1'); // false reg.test(Symbol('a1a')); // TypeError
输入: 要求输入字符串,如果输入的不是字符串类型,会尝试进行类型转换,转换失败会抛出 TypeError
输出: true 或者 false,表示匹配成功或失败 -
RegExp.prototype.source (内容) 和 RegExp.prototype.flags(修饰符并对其升序排序)
const reg = /[a-z]\d+[a-z]/ig; reg.source; // "[a-z]\d+[a-z]" reg.flags; // "gi"
-
RegExp.prototype.exec() 和 String.prototype.match()
const reg = /[a-z]\d+[a-z]/i; reg.exec('a1a'); // ["a1a", index: 0, input: "a1a", groups: undefined] reg.exec('1a1'); // null 'a1a'.match(reg); // ["a1a", index: 0, input: "a1a", groups: undefined] '1a1'.match(reg); // null
输入: RegExp.prototype.exec 要求输入字符串,遇到非字符串类型会尝试转换;
String.prototype.match 要求输入正则表达式,遇到其它类型会先尝试转成字符串,再以字符串为 source 创建正则表达式输出: 匹配成功,返回匹配结果,匹配失败,返回 null
由于 String.prototype.match 返回的数据格式不固定,因此大多数情况都建议使用 RegExp.prototype.exec
扫描二维码关注公众号,回复:
10716639 查看本文章
- RegExp.prototype.lastIndex
注意: lastIndex 不会自己重置,只有当上一次匹配失败才会重置为 0 ,因此,当你需要反复使用同一个正则表达式的时候,请在每次匹配新的字符串之前重置 lastIndex! - String.prototype.replace()、String.prototype.search()、String.prototype.split()
2. 三个应用场景
2.1 场景一:正则与数值
数值判断流程:
/[0-9]+/
:不完全匹配(只要包含数字就可)/^\d+$/
:不能匹配带符号的数值以及小数/^[+-]?\d+(\.\d+)?$/
:不能匹配无整数部分的小数(.123)/^[+-]?(?:\d*\.)?\d+$/
:不能匹配无小数部分的数值(2.)和科学计数法(-2.e+4)
完整的数值正则:
/^[+-]?(?:\d+\.?|\d*\.\d+)(?: e[+-]?\d+)?$/i
用正则处理数值:
-
数值解析
const reg = const reg = /[+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?(?=px|\s|$)/gi; function execNumberList(str) { reg.lastIndex = 0; let exec = reg.exec(str); const result = []; while (exec) { result.push(parseFloat(exec[0])); exec = reg.exec(str); } return result; } console.log(execNumberList('1.0px .2px -3px +4e1px')); // [1, 0.2, -3, 40] console.log(execNumberList('+1.0px -0.2px 3e-1px')); // [1, -0.2, 0.3] console.log(execNumberList('1px 0')); // [1, 0] console.log(execNumberList('-1e+1px')); // [-10]
-
数值转货币格式:即每到千分位加个逗号
const reg = /(\d)(?=(\d{3})+(,|$))/g; function formatCurrency(str) { return str.replace(reg, '$1,'); } console.log(formatCurrency('1')); // 1 console.log(formatCurrency('123')); // 123 console.log(formatCurrency('12345678')); // 12,345,678
2.2 场景二:正则与颜色
颜色有多少种表示方式:
-
16进制表示法
color: #rrggbb; color: #rgb; color: #rrggbbaa; color: #rgba;
const hex = '[0-9a-fA-F]'; const reg = new RegExp(`^(?:#${hex}{6}|#${hex}{8}|#${hex}{3,4})$`);
-
rgb/rgba 表示法
color: rgb(r, g, b); color: rgb(r%, g%, b%); color: rgba(r, g, b, a); color: rgba(r%, g%, b%, a); color: rgba(r, g, b, a%); color: rgba(r%, g%, b%, a%);
const num = '[+-]?(?:\\d*\\.)?\\d+(?:e[+-]?\\d+)?'; const comma = '\\s*,\\s*'; const reg = new RegExp(`rgba?\\(\\s*${num}(%?)(?:${comma}${num}\\1){2}(?:${comma}${num}%?)?\\s*\\)`);
-
其他
/* hsl & hsla */ color: hsl(h, s%, l%); color: hsla(h, s%, l%, a); color: hsla(h, s%, l%, a%); /* keywords */ color: red; color: blue; /* …… */
使用正则处理颜色:
- 16进制颜色的优化
const hex = '[0-9a-z]'; const hexReg = new RegExp(`^#(?<r>${hex})\\k<r>(?<g>${hex})\\k<g>(?<b>${hex})\\k<b>(?<a>${hex}?)\\k<a>$`, 'i'); function shortenColor(str) { return str.replace(hexReg, '#$<r>$<g>$<b>$<a>'); } console.log(shortenColor('#336600')); // '#360' console.log(shortenColor('#19b955')); // '#19b955' console.log(shortenColor('#33660000')); // '#3600'
2.3 场景三:正则与URL
解析URL:
const protocol = '(?<protocol>https?:)';
const host = '(?<host>(?<hostname>[^/#?:]+)(?::(?<port>\\d+))?)';
const path = '(?<pathname>(?:\\/[^/#?]+)*\\/?)';
const search = '(?<search>(?:\\?[^#]*)?)';
const hash = '(?<hash>(?:#.*)?)';
const reg = new RegExp(`^${protocol}\/\/${host}${path}${search}${hash}$`);
function execURL(url) {
const result = reg.exec(url);
if (result) {
result.groups.port = result.groups.port || '';
return result.groups;
}
return {
protocol: '', host: '', hostname: '', port: '',
pathname: '', search: '', hash: '',
};
}
console.log(execURL('https://www.360.cn'));
console.log(execURL('http://localhost:8080/?#'));
console.log(execURL('https://image.so.com/view?q=360&src=srp#id=9e17bd&sn=0'));
console.log(execURL('this is not a url'));
console.log(execURL('https://www.360.cn'));
{
protocol: 'http:',
host: 'www.360.cn',
hostname: 'www.360.cn',
port: '',
pathname: '',
search: '',
hash: ''
}
console.log(execURL('http://localhost:8080/?#'));
{
protocol: 'http:',
host: 'localhost:8080',
hostname: 'localhost',
port: '8080',
pathname: '/',
search: '?',
hash: '#'
}
console.log(execURL('https://image.so.com/view?q=360&src=srp#id=9e17bd&sn=0'));
{
protocol: 'https:',
host: 'image.so.com',
hostname: 'image.so.com',
port: '',
pathname: '/view',
search: '?q=360&src=srp',
hash: '#id=9e17bd&sn=0'
}
console.log(execURL('this is not a url'));
{
protocol: '',
host: '',
hostname: '',
port: '',
pathname: '',
search: '',
hash: ''
}
用正则解析search和hash:
function execUrlParams(str) {
str = str.replace(/^[#?&]/, '');
const result = {};
if (!str) {
return result;
}
const reg = /(?:^|&)([^&=]*)=?([^&]*?)(?=&|$)/y;
let exec = reg.exec(str);
while (exec) {
result[exec[1]] = exec[2];
exec = reg.exec(str);
}
return result;
}
console.log(execUrlParams('#')); // { }
console.log(execUrlParams('##')); // { '#': '' }
console.log(execUrlParams('?q=360&src=srp')); // { q: '360', src: 'srp' }
console.log(execUrlParams('test=a=b=c&&==&a=')); // { test: 'a=b=c', '': '=', a: '' }
3. 总结
如何用好正则表达式?
- 明确需求
- 考虑全面
- 反复测试