Match nth case with regex

For an app I worked on lately I implemented some Github style checkboxes in their markdown syntax.

The format is like so:

[ ] Checkbox 1
[ ] Checkbox 2
[ ] Checkbox 3

There's a couple ways you could approach this but I've gone with regular expression.

The pattern to match this is: ((\[[ x]].*?(\r\n|\r|\n)){INDEX})\[[ x]](.*)
Where INDEX is the nth we want to match -1. If we want the first, the index would be 0. 2nd would be 1, 3rd would be 2 etc.
E.g. to match the 2nd, the INDEX would be 1: ((\[[ x]].*?(\r\n|\r|\n)){1})\[[ x]](.*)

Then we can use $1[x]$4 as the replacement.

Replacing the 2nd would result in:

[ ] Checkbox 1
[x] Checkbox 2
[ ] Checkbox 3

But let's break this pattern down. The first half of this is in brackets representing the first captured group as $1 for the replace statement. In this we have \[[ x]] which matches square brackets an empty space or x inside, then .*? matches any content after it till the end of the line, followed by (\r\n|\r|\n) which detects the end of the line. This then get's repeated for the INDEX {INDEX} or {1} for matching the 2nd checkbox. The INDEX is 1 less than the value we are looking for as it starts at 0 rather than 1. This ends the first capturing group. We then we look for the checkbox again \[[ x]] as this is the one we will be replacing and grab all the content after it in a last capturing group which in the replace is $4.

Try this out at http://regexr.com/3dqac
Use the original empty checkboxes text above and the regex, then click to replace and enter the replacement script. Then try changing the index between 0, 1 and 2 to see if live replace whichever checkbox.

comments powered by Disqus
Want to setup your own server? Digital Ocean offer $100 free for new accounts.
DigitalOcean Referral Badge