【问题标题】:Catch repeated group in regex在正则表达式中捕获重复组
【发布时间】:2014-03-03 19:58:55
【问题描述】:

我有以下字符串:

{:.test1, .test2, .test3}

我使用它作为 Markdown 的扩展。对于那个字符串,我想要一个带有 ace 的语法高亮。但是我无法构建一个匹配的正则表达式来捕获正确的组。

我需要捕获的是:{: 作为第一组。第二组中的所有.test#。全部,作为第三组,最后}

我想出的当前正则表达式是:({:)(\\.\\w+)(,\\s*|)

但是这仅匹配:{:,.test1,,而不是以下 .test2,

我需要的是一个正则表达式,它捕获{:,然后是所有出现的.test1,,最后是}

目的是为逗号着色与类名不同,因此我需要捕获它。

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

还有例子:

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

这里他们匹配两组我需要但是 4 组。

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

【问题讨论】:

  • 这样的? ({:|.test\d|,|}) - regex101.com/r/tG7aW3
  • 不幸的是,这行不通,因为我确实与职位上的组完全匹配。

标签: javascript regex ace-editor


【解决方案1】:

这对于一个正则表达式是不可能的。要么使用

    {
        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*|))+}"
    }

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

【讨论】:

    【解决方案2】:

    你可以使用这个正则表达式:

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

    编辑:

    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]);
    

    【讨论】:

    • 不幸的是,这不会提取逗号。如果可能的话,我会更喜欢哪个。
    • 你不是写all occurenses of .test1 and , together吗?
    • 所以我确实写了,但不是故意的。
    • 哦,好的,您的预期输出是多少?
    • 我想匹配{:,然后是.somerandomtext的所有出现,然后是,的所有出现,最后是}
    猜你喜欢
    • 2011-09-19
    • 2017-09-13
    • 2011-03-11
    • 2017-01-07
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多