Reman
Reman

Reputation: 8109

Backwards search string

Does anyone know how to create a backwards search string using match()?

word1 word2 word3 word4
            ^

(^ = cursor position)

I want to find the start and end column of the word before the cursor (word2).

I tried this regex without success:

match(getline('.'), '?\w\ze\s', col('.')-1)

Does ? not work in a string to search backwards

Upvotes: 0

Views: 161

Answers (1)

Peter Rincker
Peter Rincker

Reputation: 45097

You are confusing the normal command ? with the function match() which works on strings. What you are actually looking for is the searchpos() function which searches for some pattern in the buffer and gives you back the position.

let [start_line, start_col] = searchpos('\<\w\+\>', 'bn')
let [end_line, end_col] = searchpos('\<\w\+\>', 'bne')

The flags mean the following:

  • b backwards
  • n don't move the cursor
  • e use the end of the match as the returned position

Please see the following for more information:

:h search(
:h searchpos(

Upvotes: 2

Related Questions