1

I have some python code with many lines like this:

print "some text" + variables + "more text and special characters .. etc"

I want to modify this to put everything after print within brackets, like this:

print ("some text" + variables + "more text and special characters .. etc")

How to do this in vim using regex?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Naren
  • 11
  • 3

2 Answers2

2

Use this substitute:

%s/print \(.*$\)/print (\1)

\(.*$\) matches everything up to the end of the line and captures it in a group using the escaped parentheses. The replacement includes this group using \1, surrounded by literal parentheses.

ib.
  • 27,830
  • 11
  • 80
  • 100
pb2q
  • 58,613
  • 19
  • 146
  • 147
1
:%s/print \(.*\)/print(\1)/c

OR if you visually select multiple lines

:'<,'>s/print \(.*\)/print(\1)/c

% - every line
'<,'> - selected lines
s - substitute
c - confirm - show you what matched before you convert
print \(.*\) - exactly match print followed by a space then group everything between the \( and \)
print(\1) - replace with print(<first match>)

Vim has some function rules for regex, you can do :help substitute or :help regex to see what they are.

evan
  • 12,307
  • 7
  • 37
  • 51