1

I have this string in my document:

subject.reset();

I am running this regex:

:%s/reset\(\)/doStuff\(\)/g

And the result looks like this:

subject.doStuff()();

Where did that extra parenthesis pair come from? I wanted it to look like this:

subject.doStuff();

How do I do that search and replace in vim?

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 1
    You don't need to escape `()` inside vim. Try `:%s/reset()/doStuff()/g` – rock321987 May 21 '16 at 03:04
  • Well, you need to escape them if your using them as a capture group, however, you're not. – l'L'l May 21 '16 at 03:06
  • @l'L'l so in vim you escape parens to mark them as capture groups? That's the opposite of most regex engines I've used. Very strange. – Daniel Kaplan May 21 '16 at 03:07
  • 1
    Yes, it's a bit odd I'll agree... `sed` works much the same way actually, which is similar to vim's regex engine. – l'L'l May 21 '16 at 03:12
  • 1
    use `\v` for regex behavior similar to other engines.. like this `:%s/\vreset\(\)/doStuff\(\)/g` to know more, check out `:h \v` – Sundeep May 21 '16 at 09:30

1 Answers1

3

You don't need to escape () inside vim. Try

:%s/reset()/doStuff()/g

or

:%s/reset/doStuff/g

\( or \) denotes capturing group inside vim. See here about capturing group.

In your example

reset\(\) actually means that you are replacing reset and a capturing group(which is empty and it does not really contain the parenthesis you intended). So, basically you are replacing only reset with doStuff()..

subject.doStuff()();
         ^^      ^^
         ||    (was already here after reset and not replaced)
     reset is replaced with do Stuff()

The parenthesis after reset is still there

Community
  • 1
  • 1
rock321987
  • 10,942
  • 1
  • 30
  • 43
  • I understand now what I did wrong, but why did it put `()()` in the replace? – Daniel Kaplan May 21 '16 at 03:08
  • 1
    @DanielKaplan `reset\(\)` actually means that you are replacing `reset` and a capturing group(_which is empty and it does not really contain the parenthesis you intended_). So it is basically you are replacing only `reset` with `doStuff()`.. the parenthesis after `reset` is still there – rock321987 May 21 '16 at 03:11