2012-03-15 30 views
2

我有幾個短語列表按照以下格式正則表達式如何分割這個單詞?

thisIsAnExampleSentance 
hereIsAnotherExampleWithMoreWordsInIt 

,我試圖用

This Is An Example Sentance 
Here Is Another Example With More Words In It 

每個短語落得有白色空間凝結和第一字母被強制爲小寫字母

我可以使用regexA-Z前添加一個空格,有這句話的第一個字母是大寫

我認爲做這樣的事情

([a-z]+)([A-Z])([a-z]+)([A-Z])([a-z]+) // etc 
$1 $2$3 $4$5 // etc 

,但對50條記錄的不同長度,我的想法是一個貧窮的解決方案。有沒有辦法regex的方式,將更多動態謝謝

+2

什麼語言是你使用? – xanatos 2012-03-15 19:33:17

+0

迭代字符串並在每個大寫字母前添加空格可能更容易。 – Ilion 2012-03-15 19:37:48

+0

like([a-z] +)+(([A-Z])([a-z] +))*?那樣有用嗎? – Colleen 2012-03-15 19:39:06

回答

1

對於空間的問題很容易,如果你的語言支持零寬度向後看

var result = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "(?<=[a-z])([A-Z])", " $1"); 

或者即使它不支持

var result2 = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "([a-z])([A-Z])", "$1 $2"); 

我使用C#,但正則表達式應該可以在支持替換的任何語言中使用,使用$1 ... $n

但是對於低位到高位的情況,您不能直接在正則表達式中執行。你可以通過一個正則表達式得到第一個字符,如:^[a-z],但你不能把它轉化。

例如在C#中,你可以使用一個匹配評估,以改變輸入字符串做

var result4 = Regex.Replace(result, "^([a-z])", m => 
{ 
    return m.ToString().ToUpperInvariant(); 
}); 

然後,您可以甚至融合兩個一起

var result4 = Regex.Replace(@"thisIsAnExampleSentanceHereIsAnotherExampleWithMoreWordsInIt", "^([a-z])|([a-z])([A-Z])", m => 
{ 
    if (m.Groups[1].Success) 
    { 
     return m.ToString().ToUpperInvariant(); 
    } 
    else 
    { 
     return m.Groups[2].ToString() + " " + m.Groups[3].ToString(); 
    } 
}); 
我用
+0

好吧,你可以用一個perl正則表達式(在替換表達式中使用'\ U'約定 - 請參閱@ Qtax的答案,但這可能不適用,因爲我們不知道什麼語言或工具是正在使用 – 2012-03-15 21:35:49

2

一個Java片段看起來是這樣的(現在的修訂版):

result = source.replaceAll("(?<=^|[a-z])([A-Z])|([A-Z])(?=[a-z])", " $1$2"); 
result = result.substring(0, 1).toUpperCase() + result.substring(1); 

這,順便說一句,串givenProductUPCSymbol轉換成Given Product UPC Symbol - 確保您使用這種類型的東西的方式很好

最後,單行版本可能是:

result = source.substring(0, 1).toUpperCase() + source(1).replaceAll("(?<=^|[a-z])([A-Z])|([A-Z])(?=[a-z])", " $1$2"); 

此外,類似於一個在問題的評論給出的例子,該字符串hiMyNameIsBobAndIWantAPuppy將改爲Hi My Name Is Bob And I Want A Puppy

1

一個Perl例如使用Unicode字符支持:

s/\p{Lu}/ $&/g; 
s/^./\U$&/; 
相關問題