2010-12-20 14 views

Odpowiedz

65

Użyj tej s regex (zapomniałem, z którego stackoverflow Odpowiedź pozyskiwaniem go, będzie go szukać teraz):

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; 
     } 

Używam go w tym projekcie: http://www.ienablemuch.com/2010/12/intelligent-brownfield-mapping-system.html

[EDIT]

znalazłem go teraz: How do I convert CamelCase into human-readable names in Java?

Ładnie split "TodayILiveInTheUSAWithSimon", nie ma miejsca na froncie "Today":

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, " ")); 
     } 
    } 
} 

wyjściowa:

YYYToday I Live In The USA With SimonZZZ 
+0

Wielkie dzięki! Czy możesz wyjaśnić różne części regex? – Nir

18

Można tylko pętla za pośrednictwem znaków i dodać przestrzenie gdzie potrzebne:

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])"); 
} 

Próbka:

https://dotnetfiddle.net/0DEt5m

+0

Proste i łatwe do wdrożenia. Świetna odpowiedź! – MiBol

+3

Dobra odpowiedź. użyj 'return string.Join (" ", Regex.Split (value, @" (?

+0

Stary wątek, ale uznałem to za przydatne. Jest to metoda rozszerzenia, którą dostosowałem do tej odpowiedzi: 'public static string SplitCamelCase (ten ciąg znaków, delimeter string =" ") { return input.Any (char.IsUpper)? string.Join (delimeter, Regex.Split (input, "(? Anders

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

Powinieneś naprawdę użyć 'StringBuilder' zamiast tworzyć ogromną ilość napisów. – Andrew

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;  
     } 
    } 

To zajmie Unicode poprawnie.

Powiązane problemy