2010-12-20 151 views

回答

65

使用thi小號正則表達式(我忘了從StackOverflow的答案,我採購它,現在搜索一下):

public static string ToLowercaseNamingConvention(this string s, bool toLowercase) 
     { 
      if (toLowercase) 
      { 
       var r = new Regex(@" 
       (?<=[A-Z])(?=[A-Z][a-z]) | 
       (?<=[^A-Z])(?=[A-Z]) | 
       (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace); 

       return r.Replace(s, "_").ToLower(); 
      } 
      else 
       return s; 
     } 

我用它在這個項目:http://www.ienablemuch.com/2010/12/intelligent-brownfield-mapping-system.html

[編輯]

我發現它現在:How do I convert CamelCase into human-readable names in Java?

精美分裂 「TodayILiveInTheUSAWithSimon」,在 「今天」 前面沒有空間:

using System; 
using System.Text.RegularExpressions; 

namespace TestSplit 
{ 
    class MainClass 
    { 
     public static void Main (string[] args) 
     { 
      Console.WriteLine ("Hello World!"); 



      var r = new Regex(@" 
       (?<=[A-Z])(?=[A-Z][a-z]) | 
       (?<=[^A-Z])(?=[A-Z]) | 
       (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace); 


      string s = "TodayILiveInTheUSAWithSimon"; 
      Console.WriteLine("YYY{0}ZZZ", r.Replace(s, " ")); 
     } 
    } 
} 

輸出:

YYYToday I Live In The USA With SimonZZZ 
+0

非常感謝!你能解釋正則表達式的不同部分嗎? – Nir 2010-12-20 12:12:42

18

您只需通過人物循環,並增加在需要空間:

string theString = "SeveralWordsString"; 

StringBuilder builder = new StringBuilder(); 
foreach (char c in theString) { 
    if (Char.IsUpper(c) && builder.Length > 0) builder.Append(' '); 
    builder.Append(c); 
} 
theString = builder.ToString(); 
45
string[] SplitCamelCase(string source) { 
    return Regex.Split(source, @"(?<!^)(?=[A-Z])"); 
} 

樣品:

https://dotnetfiddle.net/0DEt5m

+0

簡單易用。很好的答案! – MiBol 2017-04-04 17:27:00

+3

很好的答案。使用'return string.Join(「」,Regex.Split(value,@「(?<!^)(?= [AZ](?![AZ] | $))」));'如果你不願意希望大寫縮寫被拆分。 – 2017-05-12 15:39:53

+0

舊線程,但我發現這很有用。這是我從這個答案適應的擴展方法:'公共靜態字符串SplitCamelCase(這個字符串輸入,字符串delimeter =「」) { return input.Any(char.IsUpper)? string.Join(delimeter,Regex.Split(input,「(?<!^)(?= [A-Z])」)):input; }'。這允許您指定分隔符,並且如果輸入字符串不包含任何大寫字母,將返回輸入字符串而不執行RegEx。示例用法:'var s = myString.SplitCamelCase();'或'var s = myString.SplitCamelCase(「,」);' – Anders 2017-08-04 18:47:26

2
  string str1 = "SeveralWordsString"; 
      string newstring = ""; 
      for (int i = 0; i < str1.Length; i++) 
      { 
       if (char.IsUpper(str1[i])) 
        newstring += " ";      
       newstring += str1[i].ToString(); 
      } 
+0

你應該真的使用'StringBuilder'而不是創建大量的字符串。 – Andrew 2017-03-17 03:12:41

5
public static IEnumerable<string> SplitOnCapitals(string text) 
    { 
     Regex regex = new Regex(@"\p{Lu}\p{Ll}*"); 
     foreach (Match match in regex.Matches(text)) 
     { 
      yield return match.Value;  
     } 
    } 

這將妥善處理Unicode。