当前位置:首页 > 开发 > Web前端 > JavaScript > 正文

JS正则表达式的i m g

发表于: 2013-01-29   作者:bijian1013   来源:转载   浏览:
摘要:         g:表示全局(global)模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止。         i:表示不区分大小写(case-insensitive)模式,即在确定匹配项时忽略模式与字符串的大小写。         m:表示

        g:表示全局(global)模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止。 
        i:表示不区分大小写(case-insensitive)模式,即在确定匹配项时忽略模式与字符串的大小写。 
        m:表示多行(multiline)模式,即在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项。


        实例: 

var pattern = /^a.+b$/; 
undefined 
"adfasdfasdfasdfasdf".match(pattern) 
null 
"adfasdfasdfasdfasdb".match(pattern) 
["adfasdfasdfasdfasdb"] 
"adfasdfasdfasdfasdb\r\naasdfasdfasdf".match(pattern) 
null 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
null 

var pattern = /^a.+b$/m; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
["adfasdfasdfasdfasdb"] 

var pattern = /^a.+b$/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
null 

var pattern = /^a.+b$/mg; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
["adfasdfasdfasdfasdb", "aasdfasdfasdfb"] 

       

        从这几个实例不难看出:m是多行匹配,在配合^ $的正则表达式中,强制匹配每一行的开头结束 

        但对g作用又有点迷糊了,下面是g的实例: 

var pattern = /^a.+b$/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
null 

var pattern = /a.+b$/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
["aasdfasdfasdfb"] 

var pattern = /^a.+b/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
["adfasdfasdfasdfasdb"] 

var pattern = /a.+b/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
["adfasdfasdfasdfasdb", "aasdfasdfasdfb"] 

 

附: 
^:匹配一个输入或一行的开头,/^a/匹配"an A",而不匹配"An a" 
$:匹配一个输入或一行的结尾,/a$/匹配"An a",而不匹配"an A" 

对如下执行结果还是没太弄明白: 

var pattern = /^a.+b$/g; 
undefined 
"adfasdfasdfasdfasdb\r\naasdfasdfasdfb".match(pattern) 
null

 

 

JS正则表达式的i m g

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号