简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM