我正在尝试使用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: ";"
}
});
当我在编辑器中输入时,以下内容会被突出显示。我希望前两个出现的内容有样式,但后两个不需要。 显然这个正则表达式有错误:
/\b(?:timer|counter|version)\b/gi
但我已经尝试过多种不同的方式,在其他正则表达式测试器中相同的模式是正确的。例如:https://regex101.com/r/lQ0lL8/33。有什么建议吗?
编辑 #1:
在 CodeMirror 定义中尝试了这个模式,去掉 /g 但仍然产生了相同的错��高亮。
{regex: /\b(?:timer|counter|version)\b/i, token: "keyword"}
/g
修饰符:/\b(?:timer|counter|version)\b/i
。我不知道它是否是你问题的原因,但它绝对不是必需的。除此之外,正则表达式看起来没问题。 - Alan Moore/g
修饰符虽然在这里限制了我的匹配。 - colinwurtztimerNO
做了什么?也就是说,结尾的\b
起作用了吗? - Alan Moore{regex: /\b(?:timer|counter|version)\b/i, token: "keyword"}
没有高亮显示timerNO
。看起来它似乎没有尊重开头的/b
? - colinwurtz/\b!bar/
这样的正则表达式将无法匹配任何地方,即使在foo!bar
中也不行。 - Alan Moore