js正则⽅法exec和match以及正则的匹配顺序
<script type="text/javascript">
var someText="web2.0 2.0";
var pattern=/(\w+)(\d)[.](\d)/;
var (someText);
var (someText);
var b=someText.match(pattern);
var b1=someText.match(pattern);
console.log("exec",a)
console.log(a1)
console.log("match",b)
console.log(b1)
</script>
不加全局g 结果是⼀样的都是只到第⼀个满⾜条件的字符串就返回
(exec(4)["web2.0","web","2","0", index:0, input:"web2.0 2.0", groups:undefined]
(4)["web2.0","web","2","0", index:0, input:"web2.0 2.0", groups:undefined]
match(4)["web2.0","web","2","0", index:0, input:"web2.0 2.0", groups:undefined]
(4)["web2.0","web","2","0", index:0, input:"web2.0 2.0", groups:undefined]
结果分析:不加全局结果没区别 都是返回数组 并且数组的第⼀个是整个正则表达式的匹配结果 后⾯的依次是⼦表达式的匹配结果
加了全局g 的结果
<script type="text/javascript">
var someText="web2.0 2.0";
var pattern=/(\w+)(\d)[.](\d)/g;
var (someText);
var (someText);
var b=someText.match(pattern);
var b1=someText.match(pattern);
console.log("exec",a)
console.log(a1)
console.log("match",b)
console.log(b1)
</script>
exec(4)["web2.0","web","2","0", index:0, input:"web2.0 2.0", groups:undefined]
(4)["net2.0","net","2","0", index:8, input:"web2.0 2.0",groups:undefined]
match(2)["web2.0","net2.0"]
(2)["web2.0","net2.0"]
结果分析:加了全局匹配的g
match中返回的是整个正则表达式的匹配结果 不管执⾏str.match(reg)多少次 返回的结果都是样的 不返回⼦正则表达式的结果
exec当加了全局 就等于开启了分步执⾏的操作 执⾏⼀次就返回匹配到详细数据 有⼦正则表达式返回结果 可以⼀直执(str)最后会返回null,也就是全局匹配完了 返回null 还执⾏(str)⼜会从头开始匹配结果 重复上⼀轮的步骤
看下⾯代码
<script type="text/javascript">
var str ="abc12"
var reg =/\w+(\d)/g
var a = (str);
var b = (str);
var c = (str)
var d = (str)
var e = (str)
var f = (str)
console.log(a);
console.log(b)
regex匹配console.log(c)
console.log(d)
console.log(e)
console.log(f)
</script>
结果
(2)["abc1","1", index:0, input:"abc12", groups:undefined]
(2)["net2","2", index:5, input:"abc12", groups:undefined]
null
(2)["abc1","1", index:0, input:"abc12", groups:undefined]
(2)["net2","2", index:5, input:"abc12", groups:undefined]
null
总结;match是字符串的的⽅法 str.match(reg) 当 reg = /…/g 有全局g 不会返回⼦正则表达式匹配的结果,只返回整个表达式⼀次匹配的结果
没有g 有⼦正则表达式的匹配结果
exec是正则表达式的⽅法 (str) 当reg有全局 就开启了全局查步骤 没执⾏⼀次(str) 就返回整个正则表达式和⼦正则表达式匹配的结果
另外正则查字符串的顺序
当没有全局查 g
是从左往右查字符串来匹配正则表达式的开头 然后从字符串的右边开始匹配正则表达式的末尾 当末尾匹配到了就截取这段字符 并返回
当有g
是从左往右查字符串来匹配正则表达式的开头 然后从字符串的右边开始匹配正则表达式的末尾 当末尾匹配到了就截取这段字符 并返回 然后记录这个末尾字符再整个字符串中的位置lastindex
再从整个字符串lastindex这个位置开始 从左往右匹配整个正则表达式的开头 然后从字符串的右边开始匹配正则表达式的末尾 并返回 ⼀次这样匹配
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论