<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>regexp学习</title> </head> <body> <h1>正则表达式学习regexp</h1> <script> var text="mom and dad and baby"; //模式 var pattern= /mom( and dad( and baby)?)?/gi; //exec()捕获组 var matches=pattern.exec(text); document.write(matches.index+"<br/>"); document.write(matches.input+"<br/>"); document.write(matches[0]+"<br/>"); document.write(matches[1]+"<br/>"); document.write(matches[2]+"<br/>"); document.write(text.search(pattern)+"<br/>"); //正则常用元字符 var str="hello world 2014!"; //.匹配除换行意外的所有字符 var patt0=/.*/i; document.write(str+"<br/>"); document.write(str.match(patt0)+"<br/>"); //w匹配以字母、下划线、数字的字符 var patt1=/w{5}/g; document.write(str.match(patt1)+"<br>"); //s匹配任意的空白符 var patt2=/w{5}s{1}w{5}/g; document.write(str.match(patt2)+"<br>"); //d匹配数字 var patt3=/d{4}/; document.write(str.match(patt3)+"<br>"); //^匹配字符串的开始 var patt4=/l[^dl]/; //匹配除了d、l以外前面跟l的字符 document.write(str.match(patt4)+"<br>"); /*$匹配字符串的结尾 * 写法为字符+$ */ var patt5=/w{5}sd{4}!$/; document.write(str.match(patt5)+"<br>"); //验证email地址 var email="82190@163.net" var patt6=/w*@[1]w*.com|.net/; var emailresult=email.match(patt6); document.write(emailresult); //若emailresult的长度小于原email长度则为假 </script> </body> </html>