Capitalize first letter of each word in a selection using vim

南笙酒味 提交于 2019-11-28 15:57:09

You can use the following substitution:

s/\<./\u&/g
  • \< matches the start of a word
  • . matches the first character of a word
  • \u tells Vim to uppercase the following character in the substitution string (&)
  • & means substitute whatever was matched on the LHS
ernix

:help case says:

To turn one line into title caps, make every first letter of a word
uppercase: >
    : s/\v<(.)(\w*)/\u\1\L\2/g

Explanation:

:                      # Enter ex command line mode.

space                  # The space after the colon means that there is no
                       # address range i.e. line,line or % for entire
                       # file.

s/pattern/result/g     # The overall search and replace command uses
                       # forward slashes.  The g means to apply the
                       # change to every thing on the line. If there
                       # g is missing, then change just the first match
                       # is changed.

The pattern portion has this meaning.

\v                     # Means to enter very magic mode.
<                      # Find the beginning of a word boundary.
(.)                    # The first () construct is a capture group. 
                       # Inside the () a single ., dot, means match any
                       #  character.
(\w*)                  # The second () capture group contains \w*. This
                       # means find one or more word caracters. \w* is
                       # shorthand for [a-zA-Z0-9_].

The result or replacement portion has this meaning:

\u                     # Means to uppercase the following character.
\1                     # Each () capture group is assigned a number
                       # from 1 to 9. \1 or back slash one says use what
                       # I captured in the first capture group.
\L                     # Means to lowercase all the following characters.
\2                     # Use the second capture group

Result:

ROPER STATE PARK
Roper State Park  

An alternate to the very magic mode:

    : % s/\<\(.\)\(\w*\)/\u\1\L\2/g
    # Each capture group requires a backslash to enable their meta
    # character meaning i.e. "\(\)" verses "()".
Ingo Karkat

The Vim Tips Wiki has a TwiddleCase mapping that toggles the visual selection to lower case, UPPER CASE, and Title Case.

If you add the TwiddleCase function to your .vimrc, then you just visually select the desired text and press the tilde character ~ to cycle through each case.

Try This regex ..

s/ \w/ \u&/g

There is also the very useful vim-titlecase plugin for this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!