Naren
Naren

Reputation: 11

Regex Search and replace including rest of the line in brackets

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?

Upvotes: 1

Views: 952

Answers (2)

evan
evan

Reputation: 12535

:%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.

Upvotes: 1

pb2q
pb2q

Reputation: 59617

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.

Upvotes: 2

Related Questions