javascript - 使用markjs统计某个类的正则表达式匹配数

标签 javascript regex

我正在使用mark.js作为正则表达式辅助来突出显示字符串中的匹配项。

例如:

//negative assertions
instance.markRegExp(/not significant/g, {className: "negative"});
instance.markRegExp(/not associated/g, {className: "negative"});
instance.markRegExp(/no association/g, {className: "negative"});
//positive assertions
instance.markRegExp(/is associated/g, {className: "positive"});
instance.markRegExp(/are associated/g, {className: "positive"});
instance.markRegExp(/was associated/g, {className: "positive"});

我希望能够计算匹配类别发生的次数。

documentation显示回调功能,但我不确定是否可以将其用于此目的

var options = {
"filter": function(node, term, totalCounter, counter){
    if(term === "the" && counter >= 10){
        return false;
    } else {
        return true;
    }
}
};

最佳答案

这有点简单。您可以使用 eachdone 回调,两者都提供计数器。使用 done 回调,您不需要自己计算,您会收到所有标记的数量,因此对您来说更容易。此外,done 回调的性能更好,因为不需要在每个标记上调用该函数。

代码如下:

var instance = new Mark(".context"),
  negativeCounter = 0,
  positiveCounter = 0;

//negative assertions
instance.markRegExp(/not significant/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
instance.markRegExp(/not associated/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
instance.markRegExp(/no association/g, {
  className: "negative",
  done: function(counter) {
    negativeCounter += counter;
  }
});
//positive assertions
instance.markRegExp(/is associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});
instance.markRegExp(/are associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});
instance.markRegExp(/was associated/g, {
  className: "positive",
  done: function(counter) {
    positiveCounter += counter;
  }
});

document.write("Positive counter: " + positiveCounter + ", Negative counter: " + negativeCounter);
<script src="https://cdn.jsdelivr.net/mark.js/8.8.3/mark.min.js"></script>
<div class="context">
  not significant not significant not associated no association is associated are associated was associated
</div>

以下是一些注意事项:

  1. mark.js 异步工作。理论上,您应该将 .mark() 调用嵌套在 done 回调中。但是,由于您尚未启用 iframes 选项,因此它可以工作。但这样做更安全
  2. 为了减少 .mark() 调用量并使代码更简单,您应该为负匹配创建一个正则表达式,为正匹配创建一个正则表达式,例如使用正则表达式组。

关于javascript - 使用markjs统计某个类的正则表达式匹配数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42323276/

相关文章:

javascript - FB.XFBML.parse 未捕获 [对象对象]

javascript - 使用浏览器控制台使用 Javascript 在 Facebook 中发送聊天消息

<div> 中的 JavaScript 函数悬停

regex - 如何使用正则表达式查找包含某个字母的单词?

JavaScript:检查两个字母是否是字母表中的后续字母

正则表达式必须以字母或数字开头,字符串只能有字母、数字或斜线,不能有双斜线

python - 正则表达式匹配非字母数字字符

javascript - 如何从路由/索引访问 io.emit()? express 4.15

javascript - 使用 RxJS 和 twitter-stream-api 模块订阅流

javascript - 如果已经是另一个匹配的一部分,则最短的正则表达式匹配