2013-07-03 105 views
47

在vim中,我知道我們可以使用~來大寫單個字符(如this question所述),但是有沒有辦法將每個單詞的首字母大寫使用vim進行選擇?在vim中選擇每個單詞的首字母大寫

例如,如果我想從

hello world from stackoverflow 

改變

Hello World From Stackoverflow 

我應該怎麼辦呢vim的?

回答

103

您可以使用以下替代:

s/\<./\u&/g 
  • \<單詞的開頭匹配
  • .一個字
  • \u告訴Vim爲大寫以下字符的第一個字符匹配替換字符串(&)
  • &意味着替換任何在LHS
+2

非常感謝你,特別是對每一個細節的解釋! – keelar

+0

@keelar。不客氣:) –

+0

我只是必須這樣做,並使用了一個我過度重複的宏,我知道必須有更好的方法,但我從來沒有通過正則表達式。這很棒。謝謝。 –

24

: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 

說明:

:      # 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. 

圖案部分有這個意思。

\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_]. 

結果或替換部分具有這樣的意義:

\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 

結果:

ROPER STATE PARK 
Roper State Park 

一種替代到非常魔模式:

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

這是我最感興趣的答案。我從來沒有見過這種神奇的模式。我想我會在理解答案後記錄答案。 – Greg

+0

此外,這個答案處理所有小寫字母,全部大寫或混合大小寫字符串。 – Greg

9

Vim的提示Wiki有TwiddleCase mapping將視覺選擇切換爲小寫,大寫和標題大小寫。

如果您將TwiddleCase函數添加到您的.vimrc,那麼您只需在視覺上選擇所需的文本並按波浪字符~來遍歷每個案例。

2

試試這個正則表達式..

s/ \w/ \u&/g 
+0

我喜歡的答案與使用的'&'但是,如果你的字符串字符串是開始或全部大寫開始與混合情況下,它不能正常工作。 – Greg

1

還有一個非常有用的vim-titlecase插件此。

+0

謝謝。 Smart Title Case也適用於Sublime Text。 https://github.com/mattstevens/sublime-titlecase –

相關問題