js 正则表达式 如何提取数据
作者提出的问题如下:
<span title="排名:附4">张天宁</span>
我想得到以下结果:(附4)张天宁
其实在js中,只要您理解了 正则表达式 提炼数据还是很轻松的。
在论坛中有很多同学,给一段代码,还没有进行测试,就发布出来了,这样会浪费很多同学的时间。
在这里我们都是提供已经测试好的代码。
js正则表达式完整代码1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式 提炼数据 xinbiancheng.cn</title>
</head>
<body>
<script type="text/javascript">
// 正则表达式 提炼数据 方法1
var htmlString='<span title="排名:附4">张天宁</span>';
var re=/<span title=\"排名[::](.*?)\">(.*?)<\/span>/;
var matchResult=htmlString.match(re);
// matchResult[1] 得到 附4
// matchResult[2] 得到 张天宁
if(matchResult.length>0){
alert("("+matchResult[1]+")"+matchResult[2]);
}
</script>
</body>
</html>
js 正则表达式完整代码2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式 提炼数据 xinbiancheng.cn</title>
</head>
<body>
<script type="text/javascript">
// 正则表达式 提炼数据 方法2
var htmlString='<span title="排名:附4">张天宁</span>';
var re=/(?<=排名[::]).+(?=<)/;
var matchResult=htmlString.match(re);
if(matchResult.length>0){
alert("\("+matchResult[0].replace(/[\"']>/,"\)"));
}
</script>
</body>
</html>
这两个例子,都用到了 正则表达式-捕获组(capture group) 的知识
最终都能 alert 弹出消息框为:(附4)张天宁
由于内容限制,在这里只写两种,还有很多种方法,大家自己去改写。