Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, how to match pattern only if it occurs once?

Tags:

regex

vim

I have the following text :

Line 1 : orange blackberry orange coconut
Line 2 : orange
Line 3 : blackberry coconut blackberry
Line 4 : pear orange apricot

I want to find the lines where "orange" occurs only once, i.e. lines 2 and 4 (for "blackberry", it would be line 1 only).

I tried a negative lookahead construct (orange NOT FOLLOWED BY orange) but failed miserably…

/orange\(.*orange\)\@!

gave me line 2 and 4 but also, as I should have foreseen, the second instance of orange in line 1.

How should I proceed ?

Thanks in advance

like image 262
ThG Avatar asked Jul 30 '19 17:07

ThG


1 Answers

You may use

/\(orange.*\)\@<!orange\(.*orange\)\@!

where

  • \(orange.*\)\@<! - a negative "lookbehind" that makes sure there is no orange anywhere before the current position on the line
  • orange - an orange substring
  • \(.*orange\)\@! - a negative "lookahead" that makes sure there is no orange anywhere after the current position on the line.

Very magic mode notation:

/\v(orange.*)@<!orange(.*orange)@!
like image 99
Wiktor Stribiżew Avatar answered Oct 22 '22 02:10

Wiktor Stribiżew