3

I have been trying to apply the technique offered by ib in another answer on stackoverflow, cannot get it to work in m case.

I am trying to extract a list of numbers from text with reference links in this format

[1]:www.example.com    
[2]:www.example.2.com

After extracting the numbers I wish to get the maximum value from the list so that I can find the next appropriate number to use.

It was suggested in a excellent answer here:

How to extract regex matches using Vim

to another person that the following format might work:

:let nextreflink=[] | %s/\d\zs/\=add(nextreflink,submatch(1))[1:0]/g  

However, when calling "echo new", in my case, the list is empty.

Any ideas would be very welcome!

Community
  • 1
  • 1
Simon
  • 77
  • 2

2 Answers2

1

You need to capture the number matched by \d by enclosing it in \(...\); the submatch(1) refers to the first capture. Also, you probably want to match multiple numbers \d\+ to support more than nine references.

:let nextreflink=[] | %s/\(\d\+\)\zs/\=add(nextreflink,submatch(1))[1:0]/g
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
1

The following explicitly matches "[N]" at the beginning of the line so it's a little more strict. This is similar to the answer above but it does not remove the numbers from the references (I'm not really sure what's going on with that).

let refs=[] | %s/^\[\zs\d\+\ze\]/\=add(refs, submatch(0))[-1]/g

This leaves the reference list in tact. Then you can get the next available reference with:

let next = max(refs) + 1

This does not take into account skipped numbers. If the references were [1, 2, 5] then next will be 6.

Randy Morris
  • 39,631
  • 8
  • 69
  • 76