tags:

views:

114

answers:

4

Hi guys, I'm looking for a regex that will change sth. like this:

print "testcode $testvar \n";

in

printnlog("testcode $testvar \n");

I tried %s/print\s*(.\{-});/printnlog(\1);/g but gvim says

print\s*(.\{-});

doesn't match.

Where is my fault? Is it ok to use '*' after '\s' because later '{-};' will stop the greed?

Thanks in advance.

A: 

While you can create capture groups (like you're doing), I think the easiest approach is to do the job in multiple steps, with very simple regexes and "flag" words. For example:

:%s/print "testcode.*/printnlog(XXX&XXX);/
:%s/XXXprint //
:%s/;XXX//

In these examples, I use "XXX" to indicate boundaries that should later be trimmed (you can use anything that doesn't appear in your code). The ampersand (&) takes the entire match string and inserts it into the replacement string.

I don't know about other people, but I can type and execute these three regexes faster than I can think through a capture group.

kdgregory
+4  A: 

In vim you have to prepend (, ) and | with backslash, so try

:%s/print\s*\(.\{-}\);/printnlog(\1);/g
MBO
can't believe I forgot to escape the brackets :) your regex works perfectly fine
Milde
Remove last slash from @Adam's link to work
MBO
Thanks MBO, deleted the original and fixed it below!
Adam Neal
Unless you use `\v`, then you don't have to escape everything - http://briancarper.net/blog/vim-regexes-are-awesome
Adam Neal
+1 for \v, it will save (me) a lot of backslashes in the future
Milde
A: 

Is this sufficient for your needs?

%s/print\s*\("[^"]*"\)/printnlog(\1)
catchmeifyoutry
this regex is ok also, but I already marked another answer as "accepted", not only because it was the first working regex, but it remembers to escape brackets in vim :)
Milde
+3  A: 

MBO's answer works great, but sometimes I find it easier to use the "very magic" option \v so I don't have to escape everything; makes the regex a little more readable.

See also:

Adam Neal
Great, I was searching for such feature.
Maxim Veksler
voted up your comment above, because I agree, it increases readability and saves you some time
Milde