使用vim将选中每个单词的首字母大写

kee*_*lar 67 regex vim replace find capitalize

在vim中,我知道我们可以使用~大写单个字符(如本问题中所述),但是有没有办法使用vim来大写选择中每个单词的第一个字母?

例如,如果我想改变

hello world from stackoverflow
Run Code Online (Sandbox Code Playgroud)

Hello World From Stackoverflow
Run Code Online (Sandbox Code Playgroud)

我应该怎样在vim中做到这一点?

Roh*_*ain 143

您可以使用以下替换:

s/\<./\u&/g
Run Code Online (Sandbox Code Playgroud)
  • \< 匹配单词的开头
  • . 匹配单词的第一个字符
  • \u 告诉Vim在替换字符串中大写以下字符 (&)
  • & 意味着替代LHS上匹配的任何东西

  • 非常感谢你,尤其是解释每一个细节! (4认同)
  • 我不得不在vim中使用大写字母\ U来实现此功能. (4认同)
  • 可以在整个文件“%s / \ &lt;./ \ u&/ g”中进行操作 (2认同)

ern*_*nix 37

:help case 说:

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

说明:

:                      # 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.
Run Code Online (Sandbox Code Playgroud)

图案部分具有这种含义.

\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_].
Run Code Online (Sandbox Code Playgroud)

结果或替换部分具有以下含义:

\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
Run Code Online (Sandbox Code Playgroud)

结果:

ROPER STATE PARK
Roper State Park  
Run Code Online (Sandbox Code Playgroud)

非常神奇模式的替代品:

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

  • 这是对我来说最有趣的答案.我从未见过非常神奇的模式.在我理解答案之后,我以为我会记录答案. (3认同)

Ing*_*kat 10

Vim Tips Wiki有一个TwiddleCase映射,可以将视觉选择切换为小写,大写和标题大小写.

如果您将TwiddleCase功能添加到您的.vimrc,那么您只需在视觉上选择所需的文本,然后按波浪号字符~循环浏览每个案例.