6

当字符串中有大写字符或下划线时,我想添加一个空格。

我该怎么做呢?

例 1

输入

ThisIsAnInputString

输出(结果)

This Is An Input String

例 2

输入

This_Is_An_Input_String

输出(结果)

This Is An Input String
4

6 回答 6

13

您可以使用匹配一个小写字符后跟一个大写字符的正则表达式,并在以下之间添加一个可选的下划线:

string output = Regex.Replace(input, "([a-z])_?([A-Z])", "$1 $2");

您可能还想使用它来处理单个字符的单词:

string output = Regex.Replace(input, "(?<!^)_?([A-Z])", " $1");
于 2013-02-18T23:14:08.187 回答
3

下划线:

string inputString = "This_Is_An_Input_String";
string resultString = inputString.Replace('_', ' ');

首都:

string inputString = "ThisIsAnInputString";
//this will put a space before all capitals that are preceded by a lowercase character
string resultString = Regex.Replace(inputString, @"([a-z])([A-Z])", "$1 $2");
于 2013-02-18T23:31:04.687 回答
1

根据您的规格,您想在任何大写字符之前添加一个空格。这也应该适用于第一个字母。所有下划线都应替换为空格。这里的大多数答案都省略了第一个空格(之前This)。

var pattern = "([a-z?])[_ ]?([A-Z])";

var input = "ThisIsATest";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is A Test"

var input = "This_Is_A_Test";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is A Test"

var input = "ThisIsAnInputString";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is An Input String"

var input = "This_Is_An_Input_String";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is An Input String"

如果您不希望开头有多余的空间,请使用TrimStart

var input = "This_Is_A_Test";
var output = Regex.Replace(input, pattern, "$1 $2").TrimStart(' ');
// output = "This Is A Test"

编辑(更新):

我已将不同的正则表达式建议编译到一个小型测试应用程序中以验证结果:

static void Main(string[] args)
{
  const string expectedResult = "This Is A Test";
  var samples = new string[][]
      {
        new [] {"This Is A Test", "This Is A Test"},
        new [] {"ThisIsATest", "This Is A Test"},
        new [] {"This_Is_A_Test", "This Is A Test"},
        new [] {"ThisIsA_Test", "This Is A Test"},
        new [] {"This_IsATest", "This Is A Test"},
        new [] {"_ThisIsATest", "This Is A Test"},
        new [] {"_This_Is_A_Test", "This Is A Test"},
        new [] {"Thi_s_Is_A_Test", "Thi s Is A Test"},
        new [] {"T hi_s_Is_A_Te s_ t", "T hi s Is A Te s  t"}
      };

  foreach (var input in samples)
  {
    Console.WriteLine(input[0] + " => " + input[1]);

    // Guffa 1 1/9 correct.
    Console.WriteLine("Guffa 1:         " + (Regex.Replace(input[0], @"([a-z])_?([A-Z])", "$1 $2") == input[1]));

    // Guffa 2 4/9 correct.
    Console.WriteLine("Guffa 2:         " + (Regex.Replace(input[0], @"(?<!^)_?([A-Z])", " $1") == input[1]));

    // Abe Miesler 1/9 correct.
    Console.WriteLine("Abe Miesler:     " + (Regex.Replace(input[0], @"([a-zA-Z])_?([A-Z])", "$1 $2") == input[1]));

    // AppDeveloper 2/9 correct. (Not entirely fair since it was not meant for underscores).
    Console.WriteLine("AppDeveloper:    " + (Regex.Replace(input[0], @"_([A-Z])", " $1") == input[1]));

    // sparky68967 1/9 correct. (Not entirely fair since it was not meant for underscores).
    Console.WriteLine("sparky68967:     " + (Regex.Replace(input[0], @"([a-z])([A-Z])", "$1 $2") == input[1]));

    // p.s.w.g 4/9 correct.
    Console.WriteLine("p.s.w.g:         " + (Regex.Replace(Regex.Replace(input[0], @"([A-Z]+)([A-Z][a-z])", "$1_$2"), "_", " ") == input[1]));

    // Sani Huttunen 1 7/9 correct.
    Console.WriteLine("Sani Huttunen 1: " + (Regex.Replace(input[0], @"([a-z]?)[_ ]?([A-Z])", "$1 $2").TrimStart(' ') == input[1]));

    // Sani Huttunen 2 9/9 correct.
    Console.WriteLine("Sani Huttunen 2: " + (Regex.Replace(input[0].Replace('_', ' '), @"(?<!^)[ ]?([A-Z])", " $1").TrimStart(' ') == input[1]));

    Console.WriteLine();
  }
}
于 2013-02-19T00:47:34.193 回答
0

对于输入类型:ThisIsAnInputString

        string input1 = "ThisIsAnInputString";
        StringBuilder builder = new StringBuilder();

        foreach (char c in input1)
        {
            if (Char.IsUpper(c))
            {
                builder.Append(' ');
                builder.Append(c);
            }
            else
            {
                builder.Append(c);
            }
        }

        string output = builder.ToString().Trim();

对于输入类型:This_Is_An_Input_String

string input2 = "This_Is_An_Input_String";
string output = Regex.Replace(input2, "_([A-Z])", " $1");
于 2013-02-18T23:09:57.083 回答
0
    // check if string is empty
        if (string.IsNullOrEmpty(input))
            return string.Empty;


        if (input.Contains('_'))
        {
            return input.Replace('_', ' ');
        }
        else
        {
            StringBuilder newString = new StringBuilder();
            foreach (Char char1 in input)
            {
                if (char.IsUpper(char1))
                    newString.Append(new char[] { ' ', char1 });
                else
                    newString.Append(char1);
            }

            newString.Remove(0, 1);
            return newString.ToString();
        }
于 2013-02-18T23:18:21.877 回答
0
    static void Main(string[] args)
    {
        String str = "ThisIsAnInputString";
        String str2 = "This_Is_An_Input_String";

        Console.WriteLine(str);
        Console.WriteLine(str2);

        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();

        str.ToCharArray().ToList().ForEach(c => sb.Append(c == '_' ? " " :  char.IsLower(c) ? c.ToString() : " " + c.ToString()));
        str2.ToCharArray().ToList().ForEach(c => sb2.Append(c == '_' ? " " : char.IsLower(c) ? c.ToString() : " " + c.ToString()));

        str = sb.ToString().Trim(" ".ToCharArray());
        str2 = sb2.ToString().Trim(" ".ToCharArray());

        Console.WriteLine(str);
        Console.WriteLine(str2);



        Console.Read();
    }
于 2013-02-18T23:18:26.863 回答