CodeMirror简易模式 - 正则表达式未按预期高亮显示

5

我正在尝试使用CodeMirror简单模式创建自己的编辑器并突出显示一些自定义关键字。然而,它会在其他单词中突出显示这些单词的出现。以下是定义编辑器模式的代码:

    CodeMirror.defineSimpleMode("simple", {
  // The start state contains the rules that are intially used
  start: [
    // The regex matches the token, the token property contains the type
    {regex: /["'](?:[^\\]|\\.)*?(?:["']|$)/, token: "string"},
    {regex: /;.*/, token: "comment"},
    {regex: /\/\*/, token: "comment", next: "comment"},

    {regex: /[-+\/*=<>!]+/, token: "operator"},
    {regex: /[\{\[\(]/, indent: true},
    {regex: /[\}\]\)]/, dedent: true},

    //Trying to define keywords here
    {regex: /\b(?:timer|counter|version)\b/gi, token: "keyword"} // gi for case insensitive
  ],
  // The multi-line comment state.
  comment: [
    {regex: /.*?\*\//, token: "comment", next: "start"},
    {regex: /.*/, token: "comment"}
  ],
  meta: {
    dontIndentStates: ["comment"],
    lineComment: ";"
  }
});

当我在编辑器中输入时,以下内容会被突出显示。我希望前两个出现的内容有样式,但后两个不需要。

enter image description here

显然这个正则表达式有错误:
/\b(?:timer|counter|version)\b/gi

但我已经尝试过多种不同的方式,在其他正则表达式测试器中相同的模式是正确的。例如:https://regex101.com/r/lQ0lL8/33。有什么建议吗?

编辑 #1:

在 CodeMirror 定义中尝试了这个模式,去掉 /g 但仍然产生了相同的错��高亮。

{regex: /\b(?:timer|counter|version)\b/i, token: "keyword"}

1
你应该去掉/g修饰符:/\b(?:timer|counter|version)\b/i。我不知道它是否是你问题的原因,但它绝对不是必需的。除此之外,正则表达式看起来没问题。 - Alan Moore
@AlanMoore 谢谢,我尝试过了,但仍然得到了相同的结果。移除 /g 修饰符虽然在这里限制了我的匹配 - colinwurtz
它对单词 timerNO 做了什么?也就是说,结尾的 \b 起作用了吗? - Alan Moore
1
@AlanMoore 这个模式 {regex: /\b(?:timer|counter|version)\b/i, token: "keyword"} 没有高亮显示 timerNO。看起来它似乎没有尊重开头的 /b - colinwurtz
1
我怀疑它把匹配的开头当作字符串的开头。如果是这样的话,那么像 /\b!bar/ 这样的正则表达式将无法匹配任何地方,即使在 foo!bar 中也不行。 - Alan Moore
1个回答

6

最终我决定从头开始定义自己的模式,额外的自定义似乎起到了作用。我按单词解析流,将其转换为小写,然后检查它是否在我的关键字列表中。使用这种方法,添加其他样式和关键字似乎非常简单。

var keywords = ["timer", "counter", "version"];

CodeMirror.defineMode("mymode", function() {

  return {
    token: function(stream, state) {
      stream.eatWhile(/\w/);

      if (arrayContains(stream.current(), keywords)) {
        return "style1";
      }
      stream.next();
    }
  };

});


var editor = CodeMirror.fromTextArea(document.getElementById('cm'), {
  mode: "mymode",
  lineNumbers: true
});

function arrayContains(needle, arrhaystack) {
  var lower = needle.toLowerCase();
  return (arrhaystack.indexOf(lower) > -1);
}

Working Fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接