RegExp 对象的三个方法:compile()、exec()、test()
2016-06-01 09:31
375 查看
这三个都是RegExp对象下的三个方法,使用方法是一致得。
使用方法:RegExpObject.方法()
方法解析:其实就是根据定义好的正则对象,调用对应的方法。
1.RegExpObject.compile(RegExp,modifier)
modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。
compile用于改变和重新编译正则表达式。
输出:
对patt正则进行重新编译赋给patt
先是用person替换了man,然后重新定义patt正则,加了wo ,之后再次替换,这样man和woman都被替换掉了,其实可以直接写/(wo)?man/g这个正则,就能全部替换了。
2.RegExpObject.exec(string)
这个方法用于检索字符串中的正则表达式的匹配。匹配成功有值的话返回一个数组,里头存放匹配的结果,如果没找到匹配项则返回null.
输出:["W3School"]
在str字符串中查找patt正则定义字符串,找到返回字符串数组
3.RegExpObject.test(string)
test方法跟exec的区别就是返回值不同,exec找到返回值数组,test找到返回true,没找到返回false
输出:true
使用方法:RegExpObject.方法()
方法解析:其实就是根据定义好的正则对象,调用对应的方法。
1.RegExpObject.compile(RegExp,modifier)
modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。
compile用于改变和重新编译正则表达式。
var str="Every man in the world! Every woman on earth!"; patt=/man/g; str2=str.replace(patt,"person"); document.write(str2+"<br />"); patt=/(wo)?man/g; patt.compile(patt); str2=str.replace(patt,"person"); document.write(str2);
输出:
Every person in the world! Every woperson on earth! Every person in the world! Every person on earth!
对patt正则进行重新编译赋给patt
先是用person替换了man,然后重新定义patt正则,加了wo ,之后再次替换,这样man和woman都被替换掉了,其实可以直接写/(wo)?man/g这个正则,就能全部替换了。
2.RegExpObject.exec(string)
这个方法用于检索字符串中的正则表达式的匹配。匹配成功有值的话返回一个数组,里头存放匹配的结果,如果没找到匹配项则返回null.
var str = "Visit W3School"; var patt = new RegExp("W3School","g"); console.log(patt.exec(str))
输出:["W3School"]
在str字符串中查找patt正则定义字符串,找到返回字符串数组
3.RegExpObject.test(string)
test方法跟exec的区别就是返回值不同,exec找到返回值数组,test找到返回true,没找到返回false
var str = "Visit W3School"; var patt1 = new RegExp("W3School"); console.log(patt1.test(str))
输出:true
相关文章推荐
- 配置spark源码阅读windows环境
- 文件的打开保存另存为功能代码实现
- 深入理解PHP原理之执行周期分析
- iOS开发 - 清除缓存
- redis学习
- Delphi png、bmp、gif等图片格式转换成jpg
- 【转载】大型网站架构系列:消息队列(二)
- iOS中UIWebView网页加载组件的基础及使用技巧实例
- bootbox自定义dialog、confirm、alert样式,以及基本设置方法setDefaults中可用参数
- mybatis学习
- 物理cpu 逻辑cpu cpu核数
- spring注解
- 数据流向可视化
- Jsp9个内置对象详解
- 你真的了解load方法么?
- Linux学习总结(5)——CentOS常用的目录文件操作命令
- Linux学习总结(5)——CentOS常用的目录文件操作命令
- Linux学习总结(5)——CentOS常用的目录文件操作命令
- HDU 5715 XOR 游戏 二分+字典树
- 4.spark hash shuffer 解析