How do I use a regex to capture the nth pattern on each line?
background:
For syntax highlighting in Sublime Text,
you can write a file tmLanguage
with the corresponding tmTheme
file.
The file tmLanguage
contains regular expressions where you specify names,
and then the file tmTheme
uses those names to style what has been captured.
I want to color the same pattern differently depending on how many repeating patterns are in front of it. Or, to put it another way, I want to stroke the nth match of each pattern on each line differently.
problem:
So, for example,
How can I write 3 regexps to match the following bold groups?
<foo> <bar <baz>
<foo> <bar> <baz>
<foo> <bar> <baz>
everything can be inside <>.
expression 1 will capture the first instance <*.?>
expression 2 will capture the second instance <*.?>
expression 3 will capture the third instance<*.?>
Suppose the three examples above are actually the same string. My goal is to get each group a different color.
<this would be red> <this would be orange> <this would be yellow> <etc..>
The regular expression language Oniguruma .
My attempts:
I can grab the first group like this:
^<.*?>
I cannot find out how to capture only the second group
^<.*?>{2} captures nothing
<.*?>{2} captures nothing
<.*?>{2,} captures nothing
^(?:<.*?>)<.*?> captures 1st and 2nd
^(?!<.*?>)<.*?> captures nothing
^(?=<.*?>)(<.*?>) captures 1st
^(?=<.*?>)(<.*?>){1} captures 1st
^(?=<.*?>)(<.*?>){2} captures 1st and 2nd
(?=<.*?>)(<.*?>) captures everything
source to share