参考文章:
字符
- 元字符
- 反义字符
- 转义字符
- 重复匹配
- 分组/捕获
- 贪婪与惰性
- 修饰符
RegExp
定义正则表达式有两种方式:
- 字面量形式:
var pattern = /.\w/gi;
; - RegExp 构造函数形式:
var pattern = new RegExp('.\\w', 'gi');
。
正则对象(使用 RegExp 构造函数创建)方法有:
pattern.test(string)
:对传入的 string 字符串进行模式匹配,返回一个布尔值,表示字符串是否匹配该正则。pattern.exec(string)
:返回一个匹配项数组。
字符串对象的match()
、search()
、split()
及replace()
等方法也与正则表达式相关。
常用正则表达式
数字
校验数字:
var regExp = /^[0-9]*$/;
console.log(regExp.test('110')); // 输出: true
检验至少m位且至多n位数字:
var regExp = /^\d{3,5}$/; // "{m,n}"设置上下限可约束范围
console.log(regExp.test('110')); // 输出: true
console.log(regExp.test('11')); // 输出: false
console.log(regExp.test('111110')); // 输出: false
检验浮点数:
var regExp = /^(-?\d+)(\.\d+)$/;
console.log(regExp.test('11.0')); // 输出: true
console.log(regExp.test('0.11')); // 输出: true
console.log(regExp.test('-11.0')); // 输出: true
console.log(regExp.test('-0.11')); // 输出: true
console.log(regExp.test('11')); // 输出: false
其他
检验
YYYY-MM-DD HH-mm
格式的时间戳:var regExp = /^\d{4}-\d{1,2}-\d{1,2}\s\d{2}:\d{2}$/;
console.log(regExp.test('2018-04-23 23:00')); // 输出: true
检查 HTML 标签和匹配
#id
形式的字符串:var regExp = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;
console.log(regExp.exec('<h1></h1>')); // 输出: ["<h1></h1>", "<h1></h1>", undefined]
console.log(regExp.exec('#head')); // 输出: ["#head", undefined, "head"]
匹配最外层 HTML 标签名:
var regExp = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;
console.log(regExp.exec('<h1><span></span></h1>')[1]); // 输出: "h1"
匹配校验手机号:
var regExp = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
console.log(regExp.test('13415156317')); // 输出: true
匹配电子邮箱:
var regExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
console.log(regExp.test('13415156317@163.com')); // 输出: true