最近在做项目,用到了正则表达式,以前没有咋用过,所以不太熟,不说废话,直接说例子,一段文字:fasjfdhasljfhasldfhalkfdhas javascript akjdfkafhjsak;fa http https sfja;skldfjas;dfjaskdjakjdas
第一种方法:
数据文件:
module.exports = {
"labels": {
"JavaScript": [ "JavaScript",/ES ?6/ ],
"HTTP": [ /http[^:]/],
"HTML": [ "HTML","HTML5" ],
}
};
写匹配正则函数:
function label(article) {
var htmltext = article;
var labels = [];
for (var prop in objlabels) {
var count = 0;
var arrlabel = objlabels[prop];
var len = arrlabel.length;
for (var i = 0; i < len; i++) {
if(typeof(arrlabel[i]) != "string") {
pattern = arrlabel[i].source;
pattern = new RegExp(pattern,'gi');
console.log("处理过的pattern = " + pattern);
console.log("处理过的pattern类型" + typeof(pattern));
} else {
var pattern = new RegExp(arrlabel[i],'gi');
console.log("正常pattern = " + pattern);
console.log("正常的pattern类型" + typeof(pattern));
}
var ret = htmltext.match(pattern);
if (ret) {
console.log("reg = "+ret);
count += ret.length;
}
}
}
}
}
第二种方法:
数据文件:
module.exports = {
"labels": {
"JavaScript": [ "JavaScript","ES ?6"],
"HTTP": ["http[^:]"],
}
};
匹配正则函数:
function label(article) {
var htmltext = article;
var labels = [];
for (var prop in objlabels) {
var count = 0;
var arrlabel = objlabels[prop];
var len = arrlabel.length;
for (var i = 0; i < len; i++) {
var pattern = new RegExp(arrlabel[i],'gi');
console.log("pattern = " + pattern);
console.log("pattern类型" + typeof(pattern));
var ret = htmltext.match(pattern);
if (ret) {
count += ret.length;
}
}
}
}
var pattern = RegExp(“http”,’gi’);
这个pattern是一个正则对象,所以第二种方法会比较好用,因为没有类型的转换,不用分析两种情况。
请多多鼓励^_^