我正在尝试使用 CodeMirror simple mode创建我自己的编辑器并突出显示一些自定义关键字。但是,它会突出显示这些词在其他词中的出现。这是我定义编辑器模式的代码:
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"}
最佳答案
我最终只是从头开始定义我自己的模式,额外的定制似乎奏效了。我按单词解析流,转换为小写,然后检查它是否在我的关键字列表中。使用这种方法添加额外的样式和关键字似乎非常简单。
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);
}
关于javascript - CodeMirror 简单模式 - 正则表达式未按预期突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40745759/