正则表达式示例
2025年4月30日大约 1 分钟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>正则表达式</title>
</head>
<body>
<input type="text" name='tel' id='tel' placeholder='请输入手机号'>
<br/>
<hr/>
<script type="text/javascript">
//获取输入的文档元素
var tel=document.getElementById('tel');
//获取焦点事件
tel.onfocus=function()
{
tel.style.border='solid 2px blue';
}
//焦点失去事件
tel.onblur=function()
{
//获取手机号
var tn=tel.value;
//正则匹配
var preg=/^1[34578]\d{9}$/;
//执行检测
var dd=preg.test(tn);
if(dd)
{
this.style.border="solid 2px green";
}
else
{
this.style.border="solid 2px red";
this.value="";
this.placeholder="请输入正确的手机号!";
}
}
</script>
<script type="text/javascript">
document.write('<hr/>');
var str="i love you";
//第一种声明方式
var reg=new RegExp('love');
var a=reg.exec(str);
console.log(a);
//第二种声明方式 匹配普通字符
var str1="i Love you i love you to";
//i 不区分大小写
var reg1=/love/i;
var b=reg1.exec(str1);
console.log(b);
//g 进行全局匹配
var reg2=/love/g;
var c=reg2.exec(str1);
console.log(c);
//匹配手机号
var str2='15688523140';
var reg3=/^1[34578]\d{9}$/;
var d=reg3.exec(str2);
document.write(d+"<br/>");
//匹配邮箱 括号作用 提升优先级 子存储 重复单元模式
var str3='1696573873@qq.com';
var reg4=/([\w]+)@(([a-zA-Z0-9]+)\.){1,2}[a-z]{2,3}/;
var e=reg4.exec(str3);
document.write(e+"<br/>");
//匹配汉字
var str4="锄禾日当午,汗滴禾下土.";
var reg5=/([\u4e00-\u9fa5]+)[\W]+/g;
var f=reg5.exec(str4);
document.write(f+"<br/>");
//匹配url地址
var str5="<a href='http://www.baidu.com/'>百度</a>";
document.write(str5+"<br/>");
var reg6=/<a href=(['|"](.+)['|"])>([\u4e00-\ufa95]+)<\/a>/;
var g=reg6.exec(str5);
document.write(g+"<br/>");
</script>
</body>
</html>