正则表达式的创建方式有两种,见下代码:
//通过构造函数的形式创建一个正则规则
var reg = new RegExp("hello");
//通过字面量的形式创建一个正则规则
// var reg = /hello/;
var str = "hello linux";
//用正则规则去匹配字符串
var result = reg.test(str);
console.log(result);//true
元字符:拥有特殊意义的字符,我这里举例\d,\D,\w,\W,\s,\S,想要了解更多的元字符,请点击下方链接。
http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp
\d和\D的用法:
\d:匹配数字
\D:匹配非数字
// \d:查找数字(只要有数字就匹配)
//The first example:
var reg = /\d/;
var str = "hello21133";
//用正则规则去匹配字符串
var result = reg.test(str);
console.log(result);//true
//The second example:
// 匹配连续的三个数字
var reg = /\d\d\d/;
var str = "hello21133";
var result = reg.test(str);
console.log(result);//true
//The third example:
// 匹配字符b后面跟连续的三个数字
var reg = /b\d\d\d/;
var str = "hellob21133";
var result = reg.test(str);
console.log(result);//true
//\D:匹配非数字
var reg = /\D/;
var str = "hello23423";
var results = reg.test(str);
console.log(results);
\w和\W的用法:
\w:匹配数字,字母,下划线
\W:匹配非数字,字母,下划线
//\w:匹配数字,字母,下划线
//The first example:
var reg = /\w/;
var str = "hello_23423";
var results = reg.test(str);
console.log(results);//true
//The second example:
var reg = /\w\d\d/;
var str = "hello_132321";
var results = reg.test(str);
console.log(results);//true
//\W:匹配非数字,字母,下划线
var reg = /\W2\d\d/;
var str = "hello$23423";
var results = reg.test(str);
console.log(results);//true
\s和\S的用法:
\s:匹配空白字符
\S:匹配非空白字符
var reg = /\s/;
var str = "hellolinux";
var result = reg.test(str);
console.log(result);
var reg = /\S\s\S/;
var str = "hello linux";
var result = reg.test(str);
console.log(result);