regexvimreplacecase-conversion

camelCase to underscore in vi(m)


If for some reason I want to selectively convert camelCase named things to being underscore separated in Vim, how could I go about doing so?

Currently I've found that I can do a search /s[a-z][A-Z] and record a macro to add an underscore and convert to lower case, but I'm curious as to if I can do it with something like:

%s/([a-z])([A-Z])/\1\u\2/gc

Thanks in advance!

EDIT: I figured out the answer for camelCase (which is what I really needed), but can someone else answer how to change CamelCase to camel_case?


Solution

  • This is a bit long, but seems to do the job:

    :%s/\<\u\|\l\u/\= join(split(tolower(submatch(0)), '\zs'), '_')/gc