Reputation: 457
Using Vim, Notepad++, or Sublime I'd like to be able to search and replace portions of a match. I think this could be done using negative lookahead but I'd like to solicit views from the community.
Say I want to replace incidents of "fall out" with "fallout" in the following examples:
A counter example:
I suppose one obvious pattern to match is:
fall out[^a-z]
But replacing matches with "fallout" here with this match would have undesirable effects, i.e. the comma, space, period, and trailing quote in the four positive examples would be erased.
How do folks typically handle this, and bonus, how would you preserve upper and lower casing in the match?
Upvotes: 4
Views: 181
Reputation: 1750
Although you could probably do what you want with a negative lookahead, I don't think you need one, you could simply use the zero-width atom \>
(see :h /\>
) to describe the end of a word.
\>
means that the previous character is the last of a word (technically the last character inside your buffer-local option 'iskeyword'
).
As for the case issue, you could use capturing groups (see :h /\(
) to capture fall
and out
, so that you can refer to them in the replacement part of your substitutions command.
It would give:
:%s/\v\c<(fall)\s+(out)>/\1\2/g
Broken down a little:
┌──────── capture `fall`
│ ┌ capture `out`
┌────┤ ┌───┤
%s/\v\c<(fall)\s+(out)>/\1\2/g
│ │
│ └─ use the text from the 2nd capturing group (will preserve the case)
└─ use the text from the 1st capturing group (will preserve the case)
\s+
describes a sequence of whitespace characters (at least one).
\c
will make the pattern case-insensitive, and \v
enables the very magic mode. Without it, you would have to escape several atoms/quantifier in the pattern.
Edit:
Actually, you could simplify the command by just removing the sequence of whitespace:
:%s/\v\c<fall\zs\s+\zeout>//g
Broken down:
%s/\v\c<fall\zs\s+\zeout>//g
│ │
│ └─ sets the end of the match
└─ sets the start of the match
This time, you use the atoms \zs
and \ze
to set the start and end of the match. See :h /\zs
and :h /\ze
for more information.
Upvotes: 5