一:知识概要
1、转义字符:
(1) . 任意字符
(2) \d 数字[0-9]
(3)\w 数字、字母、下划线[a-z0-9]
(4)\s 空格
(5)\D 非数字[^0-9]
(6)\W [^a-z0-9]
(7)\S 非空格
2、量词
{n} 正好出现n次
{n,m}最少n次,最多m次
{n,}最少n次,最多不限
+ ---> {1,}
? --->{0,1}
* ---->{0,} 不推荐使用
另外:^ 行首(字符串开头)
$ 行位(字符串结尾)
二:代码
案例1:正则1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
//js用法
var reg = new RegExp('a','i') //i ->忽略大小写
var str = 'bcAef';
alert(str.search(reg));
</script>
</head>
<body>
</body>
</html>
案例2:正则2
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
//perl用法
var reg = /a/i;
var str = 'sdgdA';
alert(str.search(reg));
</script>
</head>
<body>
</body>
</html>
案例3:正则3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
var str = '122 sdf ffd8 67 89';
var re = /\d+/g; //g ->找出所有
//量词
//+ 若干个
alert(str.match(re));
</script>
</head>
<body>
</body>
</html>
案例4:正则4
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
var str = 'asdg sdf a as df fsaa ';
var re = /a/g; //加上 g 后将所有a替换成0;
alert(str.replace(re,0));
</script>
</head>
<body>
</body>
</html>
案例5;正则5--敏感词过滤
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload =function(){
var oTxt1 = document.getElementById('txt1');
var oBtn = document.getElementById('btn');
var oTxt2 = document.getElementById('txt2');
oBtn.onclick = function (){
var reg = /北京|淘宝|地产|房产/g; //不要忘了g
oTxt2.value = oTxt1.value.replace(reg,'***');
}
}
</script>
</head>
<body>
<textarea id='txt1' rows="10" cols="40"></textarea><br />
<input id= 'btn' type="button" value="过滤"/><br />
<textarea id = 'txt2' rows="10" cols="40"></textarea>
</body>
</html>
案例6:正则6--过滤HTML标签
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script>
window.onload =function(){
var oTxt1 = document.getElementById('txt1');
var oBtn = document.getElementById('btn');
var oTxt2 = document.getElementById('txt2');
oBtn.onclick = function (){
var reg = /<[^<>]+>/g; //不要忘了g
// .表示任意字符,+表示多个字符
oTxt2.value = oTxt1.value.replace(reg,'');
}
}
</script>
</head>
<body>
<textarea id='txt1' rows="10" cols="40"></textarea><br />
<input id= 'btn' type="button" value="过滤"/><br />
<textarea id = 'txt2' rows="10" cols="40"></textarea>
</body>
</html>
案例7:邮箱校验
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onclick = function(){
var oTxt = document.getElementById("txt1");
var oBtn = document.getElementById('btn1');
oBtn.onclick = function(){
// 一串字母、数字、下划线 @ 一串字母、数字 . 一串字母
var reg = /^\w+@[a-z0-9]+\.[a-z]+$/;
//test缺陷 : 字符串中只要有一部分满足要求即判为true ,故需要加^和$
if(reg.test(oTxt.value)){
alert('邮箱格式正确');
}
else {
alert('你丫格式错了');
}
}
}
</script>
</head>
<body>
<input type = "text" id = 'txt1'/>
<input type = "button" id= "btn1" value = '校验'/>
</body>
</html>