简体   繁体   中英

Cannot match specific group in JavaScript regex

I'm using the Rainbow.js library to add syntax highlighting to LaTeX code like so:

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. 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 .

But you will only have two groups the first (\\\\(begin|end\\\\)) and the second (.*) . 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 . You should rather use a az range with the flag i which means you ignore case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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