5

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.

2
  • 1
    +1. for {-}, I forgot about that in Vim Commented Dec 4, 2009 at 14:30
  • 1
    Found a nice site for regex in vim -> vimregex.com enjoy Commented Dec 4, 2009 at 14:33

4 Answers 4

7

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

:%s/print\s*\(.\{-}\);/printnlog(\1);/g
Sign up to request clarification or add additional context in comments.

4 Comments

can't believe I forgot to escape the brackets :) your regex works perfectly fine
Thanks MBO, deleted the original and fixed it below!
Unless you use \v, then you don't have to escape everything - briancarper.net/blog/vim-regexes-are-awesome
+1 for \v, it will save (me) a lot of backslashes in the future
4

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:

2 Comments

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

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.

Comments

0

Is this sufficient for your needs?

%s/print\s*\("[^"]*"\)/printnlog(\1)

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.