正则表达式学习总结
一、背景工作上遇到一个这样的需求:
看到这个需求,我知道应该可以用正则表达式,可是由于之前没怎么用,一想到正则表达式就头大,一堆各种各样的特殊符号,似乎没有规律可循,有点难以理解。不过知道自己不能逃避,于是自己就去尝试怎么写这个正则表达式来解决我的需求,上述中提到的问题详细描述,大概就是我思考的过程,问题提出后立马有人解答,看完他们的答案后,惭愧,感觉到自己知识的欠缺,再不学习就老了(┬_┬) 二、正则表达式基础2.1 元字符介绍
2.2 量词2.2.1 常用量词
2.2.1 懒惰限定符
2.2.2 处理选项
三、正则进阶3.1 捕获分组
后向引用一个最简单,最有用的应用是提供了确定文字中连续出现两个相同单词的位置的能力。举个例子: /(b[a-zA-Z]+b)s+1b/.exec(" asd sf hello hello asd"); //["hello hello","hello"] 解释这个例子: 1、(b[a-zA-Z]+b) 是一个捕获分组,它捕获所有的单词, " asd sf hello hello asd".match(/(b[a-zA-Z]+b)/g) // ["asd","sf","hello","asd"] 注:加上/g这个处理选项是便于我理解,没有这个选项的时候,只输出第一个单词asd。 " asd sf hello hello asd".match(/(b[a-zA-Z]+b)s/g) ["asd ","sf ","hello ","hello "] 3、"1"后向引用, " asd sf hello hello asd".match(/(b[a-zA-Z]+b)s+1b/g) ["hello hello"] 说实话,这个例子花了我很长时间去理解,有一点点想通,感觉这个概念看起来容易,写起来并不容易啊。 3.2 捕获分组常有的用法(断言)
/(hello)sworld/.exec("asdadasd hello world asdasd") // ["hello world","hello"]
/(?:hello)sworld/.exec("asdadasd hello world asdasd") // ["hello world"]
/hellos(?=world)/.exec("asdadasd hello world asdasd") // ["hello "]
/hellos(?!world)/.exec("asdadasd hello world asdasd") //null world改变一下: /hellos(?!world)/.exec("asdadasd hello wosrlds asdasd") //["hello "]
/(?!<d)123/.exec("abc123 ") // ["123"] 四、Javascript中正则表达式的使用在JavaScript中定义一个正则表达式语法为: var reg=/hello/ 或者 var reg=new RegExp("hello") 接着列举一下JavaScript中可以使用正则表达式的函数,并简单介绍一下这些函数的作用。 4.1 String.prototype.search方法用来找出原字符串中某个子字符串首次出现的索引index,没有则返回-1。可以在官方文档中了解更多。 "abchello".search(/hello/); // 3 4.2 String.prototype.replace方法用来替换字符串中的子串。简单例子: "abchello".replace(/hello/,"hi"); // "abchi" 在官方文档中有提到:
所以我在文中一开始提到的需求就可以用 4.3 String.prototype.split方法用来分割字符串 "abchelloasdasdhelloasd".split(/hello/); //["abc","asdasd","asd"] 4.4 String.prototype.match方法用来捕获字符串中的子字符串到一个数组中。默认情况下只捕获一个结果到数组中,正则表达式有”全局捕获“的属性时(定义正则表达式的时候添加参数g),会捕获所有结果到数组中。 "abchelloasdasdhelloasd".match(/hello/); //["hello"] "abchelloasdasdhelloasd".match(/hello/g); //["hello","hello"] 4.5 RegExp.prototype.exec方法和字符串的match方法类似,这个方法也是从字符串中捕获满足条件的字符串到数组中,但是也有两个区别。 /hello/g.exec("abchelloasdasdhelloasd"); // ["hello"] 2、正则表达式对象(也就是JavaScript中的RegExp对象)有一个lastIndex属性,用来表示下一次从哪个位置开始捕获,每一次执行exec方法后,lastIndex就会往后推,直到找不到匹配的字符返回null,然后又从头开始捕获。 这个属性可以用来遍历捕获字符串中的子串。 var reg=/hello/g; reg.lastIndex; //0 reg.exec("abchelloasdasdhelloasd"); // ["hello"] reg.lastIndex; //8 reg.exec("abchelloasdasdhelloasd"); // ["hello"] reg.lastIndex; //19 reg.exec("abchelloasdasdhelloasd"); // null reg.lastIndex; //0 4.6 RegExp.prototype.test方法用来测试字符串中是否含有子字符串 /hello/.test("abchello"); // true 五、总结总算是对正则表达式了解了一些,要熟练掌握还需后面多多实践^_^
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |