Useful vim search regular expressions

Computing/vim tips 2013. 6. 7. 16:35

Matching as few characters as possible

In following line:

John is someone that is capable of doing it.

Regexp t.\*t matches 'that is capable of doing it', not 'that'. Because the asterisk character (\*) matches as many characters as possible.

Sometimes you just want to match that only. Use {-} instead to match as few characters as possible.

Real world example, to match member variables only. With vim, like this:

\\<m\[A-Z\].\\{-}\\>

This expression matches, for example, following words: (the yellow backgrounded are matching words)

/\*
 \* mlOwer does not match. But mCapital matches.
 \*
inline bool operator==(const FooClass &aRight) const  
{  
    return this->mWeight == aRight.mWeight;  
}  
inline bool operator!=(const FooClass &aRight) const  
{  
    return this->mWeight != aRight.mWeight;  
}  
inline bool operator>(const FooClass &aRight) const  
{  
    return this->mWeight < aRight.mWeight;  
}

Text that matches the search pattern

& represents the text that matches the search pattern.

For example, following command finds all occurrences of DataInputStream and replace them with carbon::io::DataInputStream

:%s/\\<DataInputStream\\>/carbon::io::&/g

Reference

https://vim.fandom.com/wiki/Search_and_replace

: