简体   繁体   English

无法匹配JavaScript正则表达式中的特定组

[英]Cannot match specific group in JavaScript regex

I'm using the Rainbow.js library to add syntax highlighting to LaTeX code like so: 我正在使用Rainbow.js库向LaTeX代码添加语法突出显示,如下所示:

Rainbow.extend('latex', [
    {
        'name': 'comment',
        'pattern': /%.*$/gm
    },
    {
        'name': 'storage.function',
        'pattern': /\\[A-z@]+/g
    },
    {
        'matches':
        {
            1: 'entity.name.function',
            3: 'entity.class'
        },
        'pattern': /(\\(begin|end))\s*\{(.*?)\}/g
    }
], true)

but it fails to highlight group #3 even though—by everything I see otherwise—the group is being captured. 但是,即使按我所看到的其他方式,该组也已被捕获,但它无法突出显示#3组。 Any idea what may be going wrong? 任何想法可能出了什么问题吗? Why would it match the first group but not the third? 为什么要匹配第一组而不匹配第三组?

Your problem is that you forgot to escape a second bracket so it would be /(\\\\(begin|end\\\\))\\s*\\{(.*?)\\}/g . 您的问题是您忘记了逃脱第二个括号,因此它应该是/(\\\\(begin|end\\\\))\\s*\\{(.*?)\\}/g

But you will only have two groups the first (\\\\(begin|end\\\\)) and the second (.*) . 但是您只有两个组,第一组(\\\\(begin|end\\\\))和第二组(.*) If you don't need to get the content of a group you can make it non-capturing (it will improve the performance by the way) see What is a non-capturing group? 如果您不需要获取组的内容,则可以使其不捕获(这样可以提高性能),请参阅什么是不捕获的组? What does a question mark followed by a colon (?:) mean? 问号后跟冒号(?:)是什么意思? .

For the Az range it doesn't work like a-zA-Z see character classes . 对于Az范围,它不像a-zA-Z那样起作用,请参阅字符类 You should rather use a az range with the flag i which means you ignore case. 您应该使用带有标志iaz范围,这意味着您忽略大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM