Question

I have the following string:

{:.test1, .test2, .test3}

Which I use as an extension for Markdown. For that string I want a syntax higlighting with ace. However I am not able to build a matching regex which captures the right groups.

What I need to capture is: {: as the first group. All .test# in the second group. All , as the third group and in the end }

The current regex I came up with is: ({:)(\\.\\w+)(,\\s*|)

However this matches only: {:,.test1 and , and not the following .test2 and ,

What I need is a regex which captures the {: and then all occurenses of .test1 and , and in the end }

The aim is to color the comma different from the class names, therefore I need to capture this.

See https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode

And there the example:

{
  token : ["constant", "keyword"],
  regex : "^(#{1,6})(.+)$"
} // ### Header -> constant(###), keyword( Header)

Here they match two groups I need however 4 groups.

{
  token : ["constant", "keyword", "variable", "constant"],
  regex : "unknown"
} 
// {:.test1, .test2} -> constant({:), keyword( .test1), keyword(.test2), variable(,), constant(})
Was it helpful?

Solution

this isn't possible with one regexp. Either use

    {
        onMatch : function(v) {
            var tokens = v.slice(2, -1).split(/(,\s+)/).map(function(v) {
                return {
                    value: v,
                    type: v[0]=="."? "keyword" : "variable"
                }
            })
            tokens.unshift({value: "{:", type: "constant"})
            tokens.push({value: "}", type: "constant"})
            return tokens;
        },
        regex : "{:((\\.\\w+)(,\\s*|))+}"
    }

or

this.$rules = {
    "start" : [ {
        token : "constant",
        regex : "{:",
        next : [{
            regex: "\\.\w+",
            token: "keyword"
        },{
            regex: ",",
            token: "variable"
        },{
            regex: "$|}",
            token : "constant",
            next: "pop"
        }]
    }]
};
this.normalizeRules()

OTHER TIPS

You can use this regex:

s = '{:.test1, .test2, .test3}';
m = s.match(/(\{:)((?:\.\w+[^.}]*)+)(\})/);
//=> ["{:.test1, .test2, .test3}", "{:", ".test1, .test2, .test3", "}"]

EDIT:

var re = /(\.\w+)(, *)?/g,
    words = [], commas = [],
    input = m[2];
while (match = re.exec(input)) { words.push(match[1]); commas.push(match[2]); }

console.log(m[1], words, commas, m[3]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top