Reputation: 867
I'm trying to change the case of method names for some functions from lowercase_with_underscores
to lowerCamelCase
for lines that begin with public function get_method_name()
. I'm struggling to get this done in a single step.
So far I have used the following
:%s/\(get\)\([a-zA-Z]*\)_\(\w\)/\1\2\u\3/g
However, this only replaces one _
character at a time. What I would like it a search and replace that does something like the following:
public function [gs]et
.:s/_\(\w\)/\u\1/g
(EDIT:
Suppose I have lines get_method_name()
and set_method_name($variable_name)
and I only want to change the case of the method name and not the variable name, how might I do that? The get_method_name()
is more simple of course, but I'd like a solution that works for both in a single command. I've been able to use :%g/public function [gs]et/ . . .
as per the solution listed below to solve for the get_method_name()
case, but unfortunately not the set_method_name($variable_name)
case.
Upvotes: 1
Views: 185
Reputation: 333
If I've understood you correctly, I don't know why the things you've tried haven't worked but you can use g
to perform a normal mode command on lines matchings a pattern.
Your example would be something like:
:%g/public function [gs]et/:s/_\(\w\)/\u\1/g
Update:
To match only the method names, we can use the fact that there will only be method names before the first $
, as this looks to be PHP.
To do that, we can use a negative lookbehind, @<!
:
:%g/public function [gs]et/:s/\(\$.\+\)\@<!_\(\w\)/\u\2/g
This will look behind @<!
for any $
followed by any number of characters and only match _\(\w\)
if no $
s are found.
Bonus points(?):
To do this for multiple buffers stick a bufdo
in front of the %g
Upvotes: 4
Reputation: 934
To have vi
do replace sad with happy, on all lines, in a file:
:1, $ s/sad/happy/g
(It is the :1, $
before the sed
command that instructs vi to execute the command on every line in the file.)
Upvotes: 0
Reputation: 31439
You want to use a substitute with an expression (:h sub-replace-expression
)
Match the complete string you want to process then pass that string to a second substitute command to actually change the string
:%s/\(get\|set\)\zs_\w\+/\=substitute(submatch(0), '_\([A-Za-z]\)', '\U\1', 'g')
Running the above on
get_method_name($variable_name)
set_method_name($variable_name)
returns
getMethodName($variable_name)
setMethodName($variable_name)
Upvotes: 0