How to search for one of two similar strings in Vim?

29

4

In Vim, if I want do a search that matches "planA" or "planB", I know that I can do this:

/plan[AB]

This works because the regex allows for either A or B as its set of characters.

But how can I specify one of two complete strings? For example, "planetAwesome" or "planetTerrible"?

This will match both of these, along with "planetAnythingHereAsLongAsItsJustLetters":

planet\([a-zA-Z]*\)

How can I match only strings that match "planetAwesome" or "planetTerrible" exactly?

Nathan Long

Posted 2011-02-23T22:34:28.410

Reputation: 20 371

Actually, the brackets create a character class. plan[ABC] matches planA, planB, and planC equally well. – Christopher Bottoms – 2011-02-23T22:47:14.160

@molsecules - right, thanks. I updated the question. – Nathan Long – 2011-02-23T22:53:33.527

Answers

43

/planet\(Awesome\|Terrible\)

To see the relevant documentation, issue :help /, and scroll down to the section “The definition of a pattern”.

Gilles 'SO- stop being evil'

Posted 2011-02-23T22:34:28.410

Reputation: 58 319

1Using very magic it seems like this: /\vplanet(Awesome|Terrible) – SergioAraujo – 2017-08-30T00:47:00.063

1Ah! I wasn't escaping the parentheses when I tried this. Interesting - I thought I only had to escape literal characters. – Nathan Long – 2011-02-23T23:39:40.967

1

@Nathan: Various regex engines have different rules about which characters must be escaped to make them special vs. must be escaped to make them literal (e.g. POSIX BRE vs. ERE). You can tweak the escaping requirements in Vim on a per-pattern basis by including one of the special escapes: \m, \M, \v, or \V. There is also the 'magic' option, but it is usually best to leave it alone, since it has global effect (unless overridden by one of the above flags).

– Chris Johnsen – 2011-02-24T05:51:32.793

4

To add to Gilles' answer, you might want to add a few things in there:

/\<planet\(Awesome\|Terrible\)\>

\< marks the beginning of a 'word' (essentially alphanumerics)
\> marks the end of a 'word' (essentially alphanumerics)

asoundmove

Posted 2011-02-23T22:34:28.410

Reputation: 423