2011-06-06 134 views
21

我用這個#(\s|^)([a-z0-9-_]+)#i爲大寫每個第一個字母每一個字,我想這也是大寫字母,如果它像一個破折號特殊標記後( - )正則表達式大寫首字母每一個字,之後還像一個破折號特殊字符

現在它顯示:

This Is A Test For-stackoverflow 

,我想這一點:

This Is A Test For-Stackoverflow 

任何建議/樣品給我嗎?

卻不是因親,所以儘量保持簡單,我聽不懂。

+3

您是否還需要大寫非ASCII字母('à','ü'等)?你在用什麼語言? – 2011-06-06 13:10:32

+0

你問什麼語言的正則表達式? – JohnK 2017-06-22 15:32:44

回答

17

一個簡單的解決方案是使用word boundaries

#\b[a-z0-9-_]+#i 

或者,您可以匹配只有幾個字:

#([\s\-_]|^)([a-z0-9-_]+)#i 
+0

謝謝!奇蹟般有效! – Simmer 2011-06-06 11:56:19

+1

爲什麼你匹配'-'和'_'?他們不需要大寫... – 2011-06-06 13:09:19

+2

@Tim - 我採取了藝術自由,並沒有改變OP匹配字母的方式 - 這是*可能* Sim希望將該字母作爲輸出,改變它們的顏色或其他。此外,並沒有給它那麼多想法,我只用了4分鐘':P' – Kobi 2011-06-06 14:35:27

0

嘗試#([\s-]|^)([a-z0-9-_]+)#i - 在(\s|^)空白字符(\s)或匹配該行的開始(^)。當您將\s更改爲[\s-]時,它會匹配任何空格字符或破折號。

+0

謝謝!像js中的魅力 – Simmer 2011-06-06 11:55:48

5

其實不需要匹配滿弦只是匹配這樣的第一個非大寫字母:

'~\b([a-z])~' 
+3

一樣工作,我已經添加'g' like'/ \ b([az])/ g'來大寫每個單詞 – 2014-12-06 07:53:08

+1

我喜歡你可愛的答案@StalinGino必須說這是我唯一能夠了解。 – Danish 2016-02-08 11:38:41

0

這將使

REAC德Boeremeakers

reac de boeremeakers

(?<=\A|[ .])(?<up>[a-z])(?=[a-z. ]) 

使用

Dim matches As MatchCollection = Regex.Matches(inputText, "(?<=\A|[ .])(?<up>[a-z])(?=[a-z. ])") 
    Dim outputText As New StringBuilder 
    If matches(0).Index > 0 Then outputText.Append(inputText.Substring(0, matches(0).Index)) 
    index = matches(0).Index + matches(0).Length 
    For Each Match As Match In matches 
     Try 
      outputText.Append(UCase(Match.Value)) 
      outputText.Append(inputText.Substring(Match.Index + 1, Match.NextMatch.Index - Match.Index - 1)) 
     Catch ex As Exception 
      outputText.Append(inputText.Substring(Match.Index + 1, inputText.Length - Match.Index - 1)) 
     End Try 
    Next 
14

+1 word邊界,這裏是一個可比的JavaScript解決方案。這也解釋了所有格:

var re = /(\b[a-z](?!\s))/g; 
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon"; 
s = s.replace(re, function(x){return x.toUpperCase();}); 
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon" 
+0

toUpperCase正在大寫整個單詞。這裏是解決方案: s.replace(re,function(x){return x.charAt(0).toUpperCase()+ x.slice(1);}); – Polopollo 2016-05-09 20:26:41

+1

@Polopollo,在這種情況下,正則表達式只會返回一個字母,如果它匹配但全局。所以不需要額外的編碼,它應該按原樣工作。 – 2017-04-26 19:51:00

+0

由於OP詢問過單個角色不會被大寫,因此這不起作用。只是對於像我這樣的人來這個問題。 – 2017-04-26 19:51:56

相關問題