我目前正在使用 Codemirror Simplemode定义一个模式。
我有一个想要突出显示的关键字列表,并认为我可以用我的关键字替换演示中的关键字。在替换关键字之前,我注意到正则表达式在给定关键字之前给出了接受的字符。
具体来说,我有兴趣更改以下段落:
// Rules are matched in the order in which they appear, so there is
// no ambiguity between this one and the one above
{regex: /(?:function|var|return|if|for|while|else|do|this)\b/,
token: "keyword"},
至:
// Rules are matched in the order in which they appear, so there is
// no ambiguity between this one and the one above
{regex: /\b(?:function|var|return|if|for|while|else|do|this)\b/,
token: "keyword"},
我在开头添加的“\b”是试图强制正则表达式显式解析单词。在多个正则表达式测试器中进行的测试显示以下示例正常工作:
但是,此正则表达式在 Codemirror 中失败:
我的问题:当 codemirror 在其他 rejex 测试程序中被拒绝时,为什么 codemirror 仍然在第二行中为 A"function"着色?
最佳答案
由于 JavaScript 正则表达式 API 的限制,强制正则表达式匹配从字符串中的给定位置开始的唯一方法是在其前面加上 ^
前缀,并将其与后面的子字符串匹配那个位置。这意味着当将 A
之后的标记与字符串 "function"
匹配时,您的正则表达式将被应用,并且 \b
将匹配,因为它落在字符串的开头。
('sticky' regexp 标志是 ES6 的一部分,修复了这个问题,但尚未得到广泛支持,因此 CodeMirror 不依赖它。)
关于javascript - CodeMirror 正则表达式与典型 Javascript 正则表达式解析器的行为不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406651/