Thursday, August 27, 2009

Vim RegEx Search and Replace

I have the following text:

obj.getHost()
obj.getYourHost()
obj.setHost()
obj.setYourHost()

I want to change getHost() and setHost() to getMyHost() and setMyHost(). However, I do NOT want to change getYourHost() nor setYourHost().

Following is the regex I constructed to make the change:

:1,4s/\.[sg]et\(Your\)\@!/&My/g

\.[sg]et is the part of the expression that matches either .get or .set
\(Your\)\@! is the part of the expression that is key to matching getHost() but not getYourHost()
& is the part of the expression that takes what is matched and places that match in the replacement
g means to apply the search and replace to all matches on each line


links: Vim Help
Positive and Negative Lookahead