When I search backward a pattern that contains a repetition of characters, vim doesn’t always positions on the last occurrence of the pattern in the matching line if the matching line contains repetitions of the searching pattern. More precisely, my file is


I am in the Normal Mode. My current line is D and my search is ?ababababab

After the search the cursor column position on the line with ababab ... will be 28 and not 36 as I would expect. If I’m searching backward ?abab the column position will be the right one, i.e. 42; but in this case when searching in the line after 1234 ... the column position will be 40 and not 42. If I'm searching ?ab it will react correctly.

Can someone explain this strange behavior of Vim?

I’m using Vim Version 8.2 Last change: 2022 May 13 on OpenSuse and Fedora Linux distributions. I did no settings on my own in Vim.

I think that a new tag "backward-search" would be useful. As I’m new in in stackexchange I let other experienced users to create this tag and add it to this question.

1 Answer 1


When I paste in the text and do G?ababababab, I end up on the last occurrence of ababababab, which is the one that is below the row of numbers.

So I think the issues you are pointing out is that there are many matches in the row above the numbers, but Vim only finds 3.

I see this in :help pattern.txt:

When searching backwards, searching starts at the start of the line, using the
'c' flag in 'cpoptions' as described above.  Then the last match before the
cursor position is used.

But I think the real culprit is that Vim simply doesn't consider overlapping matches; one match cannot start in the middle of another. For example, try searching for aa in the line aaaa. There are 3 occurrences of aa with overlap, but only two without.

This is actually quite normal. A few of the other RE engines I tested (Python3, Racket, Perl, Grep) also only produce two matches when asked for all matches of aa in the string aaaa.

  • Thank you a lot. You’re right. Actually in Vim backward search means the last occurrence of the pattern, searching the pattern forwards within the line, and taking the last occurrence of the pattern starting before the column position of the cursor. This leads to two strange results: 1. The found occurrence is not necessarily the last occurrence of the pattern within the line. 2. The found occurrence may contain the character at position of the cursor before the backward search. This feature might be useful, but you must be aware of it.
    – Adrian54
    Commented Jul 22, 2022 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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