一、两种创建方式: ①、RegExp var game=new RegExp("game") var game=new RegExp("game","igm") //第二个参数可接受i(忽略大小写)、g(全局匹配)、m(多行匹配)三个参数, ②、 / / var game=/game/ var game=/game/ig
二、正则测试方法 RegExp对象有两个测试方法:test() 和exec();用于字符串测试 ①、test() 接收参数为字符串,返回boolean值。参数为字符串 var pattern=/box/i; var str="this is a box" console.log(pattern.test(str)); //true 合成一条,表示为: console.log(/box/i.test("this is a Box")); ②、exec() 匹配了则返回数组,否则返回null;参数为字符串 >console.log(/box/i.exec("this is a Box")); ["Box", index: 10, input: "this is a Box"] console.log(/box/i.exec("this is a Box")=="Box"); true var arr=/box/i.exec("this is a Box");arr; ["Box"] //匹配上了返回数组 三、正则使用方法 在正则应用中,除了test()和exec()两个测试方法,还有如下使用方法:(参数都为正则) ①、match(pattern) ②、replace(pattern,replacement) ③、search(pattern) ④、split(pattern) ①、match(pattern) 匹配得到数组 var str="this is a game,Do you want to Play the Game?";console.log(str.match(/game/ig)); ["game", "Game"] var str="this is a game,Do you want to Play the Game?";console.log(str.match(/game/ig).length); 2 ②、replace(pattern,replacement) 用第二个参数替换第一个参数(第一个参数为匹配到的值) var str="this is a game,Do you want to Play the Game?";console.log(str.replace((/game/ig),"text")); this is a text,Do you want to Play the text? ③、search(pattern)查找匹配位置,返回位置,否则返回-1 var str="this is a game,Do you want to Play the Game?";console.log(str.search(/game/igm)); 10 //匹配到game,返回第一个Game的索引 var str="this is a game,Do you want to Play the Game?";console.log(str.search(/Game/)); 39 //匹配到Game,返回第一个Game的索引 var str="this is a game,Do you want to Play the Game?";console.log(str.search(/Tame/)); -1 //匹配不到,返回-1 ④、split(pattern) 已匹配到的字符为分割点,分割成数组 var arr="this is a box,it is sigh BOX!".split(/ /ig);console.log(arr); ["this", "is", "a", "box,it", "is", "sigh", "BOX!"] var arr="this is a box,it is sigh BOX!".split(/b/ig);console.log(arr); ["this is a ", "ox,it is sigh ", "OX!"]
四、正则-元字符
字符 | 匹配情况 |
. | 点字符,匹配除换行字符 外的任意字符 |
[a-z0-9] | 匹配括号内的字符集中的任意字符,即0-9或者a-z |
[^a-z0-9] | 匹配任意不在字符集内的任意字符 |
d | 匹配数字0-9 |
D | 匹配非数字,同[^0-9] |
w | 匹配字母,数字或者下划线 |
W | 匹配除字母、数字和下划线之外的字符 |