正则的贪婪,前瞻及属性详解
对正则的深入学习学习正则我们不能光看看几个修饰符就可以了,因为正则还有许多深入的知识,下面我就来为大家扒一扒。。。 正则的三种方法
.compile()的用法compile() 方法用于在脚本执行过程中编译正则表达式,也可用于改变和重新编译正则表达式。 语法RegExpObject.compile(regexp,modifier) 参数详解 regexp 正则表达式。 modifier 规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。 实例在字符串中全局搜索 "man",并用 "person" 替换。然后通过 compile() 方法,改变正则表达式,用 "person" 替换 "man" 或 "woman", 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! .exec()的用法exec() 方法用于检索字符串中的正则表达式的匹配。 语法RegExpObject.exec(string) 参数 实例我们需要找到my,并检索 var str = "hi my name is motor how are you"; var reg = /my/; reg.exec(str) 输出my .test()的用法test() 方法用于检测一个字符串是否匹配某个模式. 语法RegExpObject.test(string) 参数 实例我们需要找到my,并检索 var str = "hi my name is motor how are you"; var reg = /my/; reg.test(str) 输出true 贪婪什么是正则表达式的贪婪与非贪婪匹配 如:String str="abcaxc";
编程中如何区分两种模式默认是贪婪模式;在量词后面直接加上一个问号?就是非贪婪模式。 量词: {m,n}:m到n个 *:任意多个 +:一个到多个 ?:0或一个 前瞻正向前瞻//判断一个单词字符之后是否是数字(正向前瞻),是的话,则符合匹配,进行替换 var str = "a2*3"; var reg = /w(?=d)/g; str.replace(reg,"X"); >>result: 'X2*3' 反向前瞻//判断一个单词字符之后是否是非数字(负向前瞻),是的话,则符合匹配,进行替换 var str = "a2*3"; var reg = /w(?!d)/g; str.replace(reg,"X"); >>result: 'aX*X' 属性
sourcevar reg = /name/; reg.source 输出name lastIndexvar str = "hi my name is motor how are you"; var reg = /m/g; console.log(reg.exec(str)) console.log(reg.lastIndex) console.log(reg.exec(str)) console.log(reg.lastIndex) console.log(reg.exec(str)) console.log(reg.lastIndex) console.log(reg.exec(str)) console.log(reg.lastIndex) console.log(reg.exec(str)) console.log(reg.lastIndex) console.log(reg.exec(str)) console.log(reg.lastIndex) 输出 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |