C#正则表达式将camelCase转换为句子案例

时间:2014-11-20 13:03:23

标签: c# regex

在我的例子中 var key = new CultureInfo("en-GB").TextInfo.(item.Key)产生'Camelcase'我可以添加哪个正则表达式,它会在第二个'c'之前产生一个空格?

示例:

'camelCase'> '骆驼案'

'itIsTimeToStopNow'> “现在是时候停止了”

2 个答案:

答案 0 :(得分:3)

如何做到这一点的方法之一。

string input = "itIsTimeToStopNow";
string output = Regex.Replace(input, @"\p{Lu}", m => " " + m.Value.ToLowerInvariant());
output = char.ToUpperInvariant(output[0]) + output.Substring(1);

答案 1 :(得分:2)

一种方法是用空格大写字母替换大写字母,然后将第一个字符设为大写:

var input = "itIsTimeToStopNow";

// add spaces, lower case and turn into a char array so we 
// can manipulate individual characters
var spaced = Regex.Replace(input, @"[A-Z]", " $0").ToLower.ToCharArray();

// spaced = { 'i', 't', ' ', 'i', 's', ' ', ... }

// replace first character with its uppercase equivalent
spaced[0] = spaced[0].ToString().ToUpper()[0];

// spaced = { 'I', 't', ' ', 'i', 's', ' ', ... }

// combine the char[] back into a string
var result = String.Concat(spaced);

// result = "It is time to stop now"