Cannot match specific group in JavaScript regex

87 views Asked by At

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?

1

There are 1 answers

0
Gadcam On

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 A-z range it doesn't work like a-zA-Z see character classes. You should rather use a a-z range with the flag i which means you ignore case.