ThG
ThG

Reputation: 2401

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

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

Upvotes: 6

Views: 76

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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)@!

Upvotes: 7

Related Questions