user697911
user697911

Reputation: 10531

Why doesn't my non-greedy match work in vim?

This  is  test

There are two tabs (\t) in this line. I want to get rid of the part from the beginning to the first tab key, which is "This ", and I used the following pattern:

:s/.\{-}\t//g

It says it can't find the pattern. If I use the following, both tabs are replaced, which isn't what I want. Why doesn't the first pattern work?

:s/.*\t//g

Upvotes: 2

Views: 392

Answers (2)

Bill
Bill

Reputation: 1425

Your first attempt does not work because you are matching the fewest number of any character followed by a tab. The fewest number of any character is zero (0). So both of your tabs match without any other characters.

Based on the comments, the above explanation was incorrect.

Here is one possible solution.

:s/^[^\t]*\t//

This goes from the beginning ^, capturing any number of non-tab characters [^\t]* until it reaches a tab \t.

Upvotes: 7

sidyll
sidyll

Reputation: 59287

Your pattern /.\{-}\t didn't work because of the g flag in the :s command. This flag enables global matching so it matches twice. Just remove the flag and it will work. In addition, when deleting something you can omit the replacement part in :s:

:s/.\{-}\t

The full :s/.\{-}\t// is fine as well. Note that in either case it should not say "pattern not found" as you described. If you see that message, there is something else different between your example and your actual text.

Upvotes: 3

Related Questions