前端之家收集整理的这篇文章主要介绍了
一个跟正则有关的字符串匹配问题,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近在做项目,用到了正则表达式,以前没有咋用过,所以不太熟,不说废话,直接说例子,一段文字:fasjfdhasljfhasldfhalkfdhas javascript akjdfkafhjsak;fa http https sfja;skldfjas;dfjaskdjakjdas
第一种方法:
数据文件:
module.exports = {
"labels": {
"JavaScript": [ "JavaScript",/ES ?6/ ],
"HTTP": [ /http[^:]/],
"HTML": [ "HTML","HTML5" ],
}
};
写匹配正则函数:
@H_
301_15@
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[^:]"],
}
};
匹配正则函数:
@H_
301_15@
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是一个正则对象,所以第二种方法会比较好用,因为没有类型的转换,不用分析两种情况。
请多多鼓励^_^
原文链接:https://www.f2er.com/regex/359449.html