Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use regex to capture the nth pattern on each line?

background:

For syntax highlighting in Sublime Text,
you can write a tmLanguage file with a corresponding tmTheme file.

The tmLanguage file contains regular expressions in which you give names to,
and then the tmTheme file uses those names to style what was captured.

I want to colorize the same pattern differently depending on how many duplicate patterns came before it. Or, to put it another way, I want to style the nth match of each pattern on each line differently.

the problem:

So for example,
How can I write 3 regular expressions to match the following bold groups?

< foo >< bar >< baz >
< foo >< bar >< baz >
< foo >< bar >< baz >

anything could be inside of < >.

expression 1 would capture the first instance of <*.?>
expression 2 would capture the second instance of <*.?>
expression 3 would capture the third instance of <*.?>

Assume the three examples above are actually the same line.
My goal is to get get each group a different color

<this would be red> <this would be orange> <this would be yellow> <etc..>

The regular expression language is Oniguruma.


My attempts so far:

I can capture the first group like this:

^<.*?>

I can't find out how to capture the second group only

^<.*?>{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
like image 605
Trevor Hickey Avatar asked Oct 20 '25 10:10

Trevor Hickey


1 Answers

You can use

(?m)^(?:<[^>]*>[[:blank:]]*){1}\K<[^>]*>

To match the second value. Then, just increment the 1 to get further values.

Here is a demo

The thrid value will be matched with (?m)^(?:<[^>]*>[[:blank:]]*){2}\K<[^>]*>, etc.

like image 115
Wiktor Stribiżew Avatar answered Oct 22 '25 05:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!