exact match in regrex when using vim, man, or less

6,380

Solution 1

A shorter vim expression to ensure no characters precede or follow

/\(^\|\s\)\@<=-c\>

The man/less equivalent:

/(^|\s)-c\b

Additional explanation (Vim):

Probably the most useful part of the Vim regular expression is -c\> which simply says "Look for '-c', but only if no letters come right after". Most of the time, you can probably get away with just searching with /-c\>, but for the sake of completeness, I included an expression to check what comes before the '-c'. That expression is \(^\|\s\)\@<=, which looks complicated just because Vim's regular expression syntax is a bit more verbose (in that it requires you to escape grouping parentheses and the 'or' pipe). The expression \(^\|\s\) means "The beginning of a line or a whitespace character". When you put \@<= after it, it means "Don't really match that, just make sure it comes before the next part of the regular expression" (which is only really useful for search-and-replace operations). Practically speaking, you likely don't need the \@<= part. You could shorten it further by omitting that and adding \v, which tells Vim you won't be escaping fancy syntax. That would look like /\v(^|\s)-c>.

Explanation of the man/less equivalent:

Much simpler. For the regular expression syntax used by less (which is the default man pager), \b is the same as Vim's \>, and you don't need to escape the parentheses or pipe character. It just looks for the string '-c' which occurs at the beginning of the line or immediately after a whitespace character and makes sure no other letters come after.

Solution 2

In vim, use

/\(^\|\s\)-c\($\|\s\)

In less:

/(^|\s)-c($|\s\)

You could use isk and word boundaries in vim, but this would also match other things that might be options; it's safer to explicitly look for blanks.

Share:
6,380
user3366906
Author by

user3366906

Updated on September 18, 2022

Comments

  • user3366906
    user3366906 over 1 year

    when using vim, man, or less, I want to do some exact match in regrex

    for example, when using man, I want to check the argument '-c'

    if I use

      /'-c'
    

    the matching could be -cim -covert......blabla

    but I only want to match '-c'

    how to do the exact matching? thanks!

  • user3366906
    user3366906 about 11 years
    I tried in the man page, it doesnt work
  • clerksx
    clerksx about 11 years
    @user138126 See my update, should better fit your use case.
  • user3366906
    user3366906 about 11 years
    wow, it is so complex, can you explain it a bit or are there any good related articles on how these scripts can represent '-c'