JS正则表达式详解
1.正则语法规则
[xyz]
字符集,匹配任何一个包含的字符
[^xyz]
否定字符集,匹配未包含的字符
\w
数字字母下划线
\W
非数字字母下划线
\s
空白字符
\S
非空白字符
\d
匹配数字
\D
匹配非数字
\b
单词开头或结束的位置
\B
非单词开头或结束的位置
^
开始位置
$
结束位置
示例:简易邮箱匹配
varr=/[\w.-]@[\w.-]/
//或者
var r = new RegExp('[\w.-]@[\w.-]','');
varemali='@'
console.log(r.test(emali));//false
varemali='web@qq'
console.log(r.test(emali));//true
2.重复
*代表匹配0次或多次
+代表匹配1次或多次
?代表匹配0次或1次
{n}指定匹配次数
{n,}匹配n次或更多
{n,m}匹配n到m次
varr=/^[\w.]+@[\w.]+$/
r.test('web@qq.com')//true
3.属性flags
source--s正则的原始字符串形式
ignoreCase--i忽略大小写
global--g全局匹配,匹配后不中止
multiline--m如果字符串有换行,按多行匹配
4.方法
1.test()方法,测试指定字符串是否满足对应的正则规则
2.exec()方法,返回匹配内容等信息组成的对象
3.match()方法,这是一个字符串的方法,与exec方法作用类似,区别是对g的解释不通,exec方法使用g标记时需要多次遍历,match方法回一次返回所有匹配内容
//如下:
vartarget='bg.jpgindex.htmlapp.jsindex.csstest.jpg';
varr=/(\w+)\.jpg/g;
//match方法
console.log(target.match(r));
//结果
//(2)["bg.jpg","test.jpg"]
//exec方法
console.log(r.exec(target));
console.log(r.exec(target));
//结果
//(2)["bg.jpg","bg",index:0,input:"bg.jpgindex.htmlapp.jsindex.csstest.jpg",groups:undefined]
//(2)["test.jpg","test",index:35,input:"bg.jpgindex.htmlapp.jsindex.csstest.jpg",groups:undefined]
5.分组与捕获
1.分组的用法:
//普通写法
varr=/123123123/;
console.log(r.exec("20191231231232019"));
//分组的写法
varr=/(123){3}/
console.log(r.exec("20191231231232019"));
//除了上面的使用场景,还可以用来做'或'匹配
varr=/hello(world|js)/;
console.log(r.test("helloworld"));//true
console.log(r.test("hellojs"));//true
2.那么什么是捕获呢?看下面这个例子
使用了分组的表达式返回时除了匹配到的完整内容,还带有了捕获到哪些字符串
3.非捕获型分组
var r = /(web) say hello (world|js)/;
console.log(r.exec("web say hello world"));
//返回值 (3) ["web say hello world", "web", "world", index: 0, input: "web say hello world", groups: undefined]
//这里的world其实不需要捕获,只是用来做一个或匹配的
var r = /(web) say hello (?:world|js)/;
console.log(r.exec("web say hello world"));
//返回值 (2) ["web say hello world", "web", index: 0, input: "web say hello world", groups: undefined]
//这就是非捕获型匹配
6.贪婪匹配与惰性匹配
var str = '<span>abc</span><span>qwe</span>';
var r = /<span>.*<\/span>/;
r.exec(str);
//执行结果
["<span>abc</span><span>qwe</span>", index: 0, input: "<span>abc</span><span>qwe</span>", groups: undefined]
//匹配了最长路径,如果我们只想匹配到前面一部分,需要使用惰性匹配
var str = '<span>abc</span><span>qwe</span>';
var r = /<span>.*?<\/span>/;
r.exec(str);
//执行结果
["<span>abc</span>", index: 0, input: "<span>abc</span><span>qwe</span>", groups: undefined]
//在重复量词后面加一个?,代表使用惰性匹配,尽可能短的匹配
7.正向前瞻/负向前瞻
var target = 'bg.jgp index.html app.js index.css test.jpg'
//从以上字符串中找出以jpg结尾的文件名,这里就需要用到正向前瞻了
var r = /\b(\w+)\.jpg/g;
console.log(target.match(r));
//["bg.jpg", "test.jpg"]
var r = /\b(\w+)(?=\.jpg)/g;
console.log(target.match(r));
//["bg", "test"]
//正向前瞻语法(?=) 负向前瞻语法(?!)
//正向前瞻表示必须后面跟有指定字符才算匹配成功,负向前瞻相反,必须不匹配指定字符才算匹配成功
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。