Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Here is a start of a regex mode for CodeMirror inspired by [Regex Colorizer](
.cm-s-default{background: #aad1f7;}
.cm-s-default{background: #f9ca69;}
.cm-s-default{color: #007a09;}
.cm-s-default{background: #d2f854;}
.cm-s-default{background: #9ec70c;}
.cm-s-default{background: #ecc9f7;}
.cm-s-default{background: #54b70b;}
.cm-s-default{background: #b688cf;}
.cm-s-default{background: #ff4300;}
CodeMirror.defineMode("regex", function() {
var otherChar = /^[\^\$\.\+\?\*]/;
var g= 0;
var tokenBase = function(stream) {
var ch =;
if (ch == "\\" && stream.match(/./, false)) {
if (stream.match(/u\w{4}/)) return "a";
if (stream.match(/u/)) return "err";
if (stream.match(/x\w{2}/)) return "a";
if (stream.match(/x/)) return "err";
if (stream.match(/./)) return "a";
return "a";
if (ch == "{"){
if (stream.match(/(\d|\d,\d?)\}/)) return "a";
if (ch == "[" && stream.match(/[^\]]+\]/)){
return "b";
if (ch == "|") {
return "g" + g;
if (ch == "(") {
return "g" + (++g % 5);
if (ch == ")") {
if(g-1 < 0) return "err";
return "g" + (g-- % 5);
if (otherChar.test(ch)) {
return "a";
return {
startState: function(base) {
g= 0;
token: tokenBase
CodeMirror.defineMIME("text/x-regex", "regex");

This comment has been minimized.

Copy link

JackMorganNZ commented Mar 30, 2016

Hi @douglasduteil, just letting you know we have used your code as a starting point for an interactive in our online Computer Science Field Guide text book (repo here). We have added attribution in the interactive's README file and within these files. Hopefully that's fine, let me know if you have any issues with it. Cheers, Jack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.