CodeMirror 简单模式 - 正则表达式未按预期突出显示

col*_*rtz 5 javascript regex codemirror

我正在尝试使用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: ";"
  }
});
Run Code Online (Sandbox Code Playgroud)

当我在编辑器中输入时,这就是突出显示的内容。我希望前两次出现的样式是样式,但不是后两个。

在此处输入图片说明

这个正则表达式显然是不正确的:

/\b(?:timer|counter|version)\b/gi
Run Code Online (Sandbox Code Playgroud)

但是我已经尝试了几种不同的方法,并且相同的模式在其他正则表达式测试器中也能正常工作。示例:https : //regex101.com/r/lQ0lL8/33。有什么建议吗?

编辑#1:

在 codemirror 定义中尝试了这种模式,删除了 /g 但它仍然会产生相同的错误突出显示。

{regex: /\b(?:timer|counter|version)\b/i, token: "keyword"}
Run Code Online (Sandbox Code Playgroud)

col*_*rtz 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);
}
Run Code Online (Sandbox Code Playgroud)

工作小提琴