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上匹配的任何东西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)
Ing*_*kat 10
Vim Tips Wiki有一个TwiddleCase映射,可以将视觉选择切换为小写,大写和标题大小写.
如果您将TwiddleCase
功能添加到您的.vimrc
,那么您只需在视觉上选择所需的文本,然后按波浪号字符~
循环浏览每个案例.