c#中的正则表达式

时间:2011-08-19 06:46:40

标签: c# regex

我正在尝试使用正则表达式来转换像这样的字符串“朝鲜” 对于像“northKorea”这样的字符串 - 有人知道如何在c#中实现这个目标吗?

干杯

7 个答案:

答案 0 :(得分:7)

如果您知道所有输入字符串都是标题大小写(如“朝鲜”),您可以这样做:

string input = "North Korea"; 
input = input.Replace(" ",""); //remove spaces
string output = char.ToLower(input[0]) + 
              input.Substring(1); //make first char lowercase
                                  // output = "northKorea"

如果你的某些输入不是标题,你可以使用TextInfo.ToTitleCase

string input = "NoRtH kORea"; 
input = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
input = input.Replace(" ",""); //remove spaces
string output = char.ToLower(input[0]) + 
          input.Substring(1); //make first char lowercase
                              // output = "northKorea"

答案 1 :(得分:4)

忘掉正则表达式 您只需要一个camelCase转换算法:

见这里: http://www.codekeep.net/snippets/096fea45-b426-40fd-8beb-dec49d8a8662.aspx

使用这个:

string camelCase = ConvertCaseString(a, Case.CamelCase);

复制粘贴,以防它脱机:

void Main() {
    string a = "background color-red.brown";
    string camelCase = ConvertCaseString(a, Case.CamelCase);
    string pascalCase = ConvertCaseString(a, Case.PascalCase);
}

/// <summary>
/// Converts the phrase to specified convention.
/// </summary>
/// <param name="phrase"></param>
/// <param name="cases">The cases.</param>
/// <returns>string</returns>
static string ConvertCaseString(string phrase, Case cases)
{
    string[] splittedPhrase = phrase.Split(' ', '-', '.');
    var sb = new StringBuilder();

    if (cases == Case.CamelCase)
    {
        sb.Append(splittedPhrase[0].ToLower());
        splittedPhrase[0] = string.Empty;
    }
    else if (cases == Case.PascalCase)
        sb = new StringBuilder();

    foreach (String s in splittedPhrase)
    {
        char[] splittedPhraseChars = s.ToCharArray();
        if (splittedPhraseChars.Length > 0)
        {
            splittedPhraseChars[0] = ((new String(splittedPhraseChars[0], 1)).ToUpper().ToCharArray())[0];
        }
        sb.Append(new String(splittedPhraseChars));
    }
    return sb.ToString();
}

enum Case
{
    PascalCase,
    CamelCase
}

答案 2 :(得分:3)

你可以将它拆分并重新组合在一起:

string[] split = ("North Korea").Split(' ');

StringBuilder sb = new StringBuilder();

for (int i = 0; i < split.Count(); i++)
{
    if (i == 0)
        sb.Append(split[i].ToLower());
    else
        sb.Append(split[i]);
}

编辑:改为切换到StringBuilder,就像Bazzz建议的那样。

答案 3 :(得分:2)

这是基于Paolo Falabella作为String扩展的答案,并处理一些边界情况,例如空字符串。由于CamelCase和camelCase之间存在一些混淆,我将其称为LowerCamelCase,如维基百科所述。我拒绝接受nerdCaps的诱惑。

internal static string ToLowerCamelCase( this string input )
{
    string output = "";            
    if( String.IsNullOrEmpty( input ) == false  )
    {
        output = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase( input ); //in case not Title Case
        output = output.Replace( " ", "" ); //remove any white spaces between words
        if( String.IsNullOrEmpty( output ) == false )  //handles the case where input is "  "
        {
            output = char.ToLower( output[0] ) + output.Substring( 1 ); //lowercase first (even if 1 character string)
        }
    }
    return output;
}

使用:

string test = "Foo Bar";
test = test.ToLowerCamelCase();
... //test is now "fooBar"

<强>更新 toong在评论中提出了一个很好的观点 - 这不适用于字形。请参阅toong提供的链接。如果您想调整上面的字形代码,还有迭代字形herehere的示例。

答案 4 :(得分:1)

String::Split绝对是我的宠儿之一。此外,没有其他答案处理:

  • 文化
  • 所有形式的单词分隔符
  • 数字
  • 以单词分隔符开头时会发生什么

我试图尽可能接近基类库代码中的内容:

static string ToCamelCaseInvariant(string value) { return ToCamelCase(value, true, CultureInfo.InvariantCulture); }
static string ToCamelCaseInvariant(string value, bool changeWordCaps) { return ToCamelCase(value, changeWordCaps, CultureInfo.InvariantCulture); }

static string ToCamelCase(string value) { return ToCamelCase(value, true, CultureInfo.CurrentCulture); }
static string ToCamelCase(string value, bool changeWordCaps) { return ToCamelCase(value, changeWordCaps, CultureInfo.CurrentCulture); }

/// <summary>
/// Converts the given string value into camelCase.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="changeWordCaps">If set to <c>true</c> letters in a word (apart from the first) will be lowercased.</param>
/// <param name="culture">The culture to use to change the case of the characters.</param>
/// <returns>
/// The camel case value.
/// </returns>
static string ToCamelCase(string value, bool changeWordCaps, CultureInfo culture)
{
    if (culture == null)
        throw new ArgumentNullException("culture");
    if (string.IsNullOrEmpty(value))
        return value;

    var result = new StringBuilder(value.Length);
    var lastWasBreak = true;
    for (var i = 0; i < value.Length; i++)
    {
        var c = value[i];
        if (char.IsWhiteSpace(c) || char.IsPunctuation(c) || char.IsSeparator(c))
        {
            lastWasBreak = true;
        }
        else if (char.IsNumber(c))
        {
            result.Append(c);
            lastWasBreak = true;
        }
        else
        {
            if (result.Length == 0)
            {
                result.Append(char.ToLower(c, culture));
            }
            else if (lastWasBreak)
            {
                result.Append(char.ToUpper(c, culture));
            }
            else if (changeWordCaps)
            {
                result.Append(char.ToLower(c, culture));
            }
            else
            {
                result.Append(c);
            }

            lastWasBreak = false;
        }
    }

    return result.ToString();
}

// Tests
'  This is a test. 12345hello world' = 'thisIsATest12345HelloWorld'
'--north korea' = 'northKorea'
'!nOrTH koreA' = 'northKorea'
'System.Console.' = 'systemConsole'

答案 5 :(得分:1)

尝试以下方法:

var input = "Hi my name is Rony";
var subStrs = input.ToLower().Split(' ');
var output = "";

foreach(var s in subStrs)
{
   if(s!=subStrs[0])
      output += s.First().ToString().ToUpper() + String.Join("", s.Skip(1));
   else
      output += s;
}

应该输出“hiMyNameIsRony”作为输出

答案 6 :(得分:0)

    string toCamelCase(string s)
    {
        if (s.Length < 2) return s.ToLower();
        return Char.ToLowerInvariant(s[0]) + s.Substring(1);
    }

与Paolo Falabella的代码类似,但仍然存在空字符串和1个字符串。