31

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?

| improve this question | |
45
/planet\(Awesome\|Terrible\)

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

| improve this answer | |
  • 1
    Ah! I wasn't escaping the parentheses when I tried this. Interesting - I thought I only had to escape literal characters. – Nathan Long Feb 23 '11 at 23:39
  • 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 Feb 24 '11 at 5:51
  • 1
    Using very magic it seems like this: /\vplanet(Awesome|Terrible) – SergioAraujo Aug 30 '17 at 0:47
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)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.