I have these lines in a script:

" go to start of file and search until the end
call cursor([1,1])
let moreLinesToGo = v:true
let b:qtags = []

while (moreLinesToGo)
  " search for lines like ":344f:", ":2:", ":234hello:"
  let lineWithTag = search('^:\d\{1,4\}\a*:$')

  if lineWithTag == 0
    let moreLinesToGo = v:false
    let qtag = getbufline(bufname('.'), lineWithTag)
    " put only the numbers into b:qtags, e.g. "344", "2", "234"
    let b:qtags += [matchstr(qtag, '\d\+')]


What happens that when I execute this file, ":344f:" is put into the list. However when I execute it manually (in cmdline mode), I get "344". How can this happen? '\d+' seems to match everything??


The problem is that getbufline(...) returns a list of lines. In your case the list only contains one element. Then the second to last line from :help matchstr() is important:

When {expr} is a List then the matching item is returned.

Use let qtag = getline(lineWithTag) instead.

Another idea:

let b:myTags=map(filter(getline(1, line('$')), { idx, val -> match(val, '^:\d\{1,4\}\a*:$') >= 0 } ), { idx, val -> matchstr(val, '\d\+')})
  • getline(1, line('$')) returns a list containing all lines in the file
  • filter(...) filters the list with the given lambda
  • map(...) maps the entries to only contain the matched digits.
  • @hgiesel Could you accept this answer or is additional clarification needed? – Ralf Jan 11 at 10:11

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.