.NET-如何将以“大写”分隔的字符串拆分为数组?


114

我如何从以下字符串开始:“ ThisIsMyCapsDelimitedString”

...到此字符串:“这是我的大写字母分隔字符串”

首选使用VB.net中最少的代码行,但也欢迎使用C#。

干杯!


1
当您必须处理“ OldMacDonaldAndMrO'TooleWentToMcDonalds”时,会发生什么?
格兰特·瓦格纳

2
只会看到有限的用途。我将主要使用它来解析变量名称,例如ThisIsMySpecialVariable,
Matias Nino

这为我工作:Regex.Replace(s, "([A-Z0-9]+)", " $1").Trim()。如果要拆分每个大写字母,只需删除加号即可。
Mladen B.

Answers:


173

我前一阵子做了。它与CamelCase名称的每个组成部分匹配。

/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g

例如:

"SimpleHTTPServer" => ["Simple", "HTTP", "Server"]
"camelCase" => ["camel", "Case"]

要将其转换为仅在单词之间插入空格:

Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")

如果您需要处理数字:

/([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g

Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ")

1
骆驼香烟盒!那就是所谓的!我喜欢它!非常感谢!
Matias Nino

19
实际上,camelCase有一个前导小写字母。您在这里指的是PascalCase。
Drew Noakes

12
...而当您提及的东西可能是“驼峰式”或“帕斯卡式”时,则被称为“被封顶”
克里斯,克里斯,2010年

不拆分“ Take5”,这将使我的用例失败
PandaWood

1
@PandaWood Digits不在问题中,因此我的回答没有说​​明它们。我添加了占数字位数的模式的变体。
马库斯·贾德罗

36
Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")

到目前为止,这是最好的解决方案,但是您需要使用\\ B进行编译。否则,编译器尝试将\ B视为转义序列。
Ferruccio

不错的解决方案。谁能想到一个不应该被接受的答案的原因?是能力不足还是表现不佳?
德鲁·诺阿克斯

8
这个将连续的大写字母视为单独的单词(例如ANZAC为5个单词),而MizardX的答案将其作为一个单词(正确的IMHO)对待。

2
@Ray,我认为“ ANZAC”应写为“ Anzac”,因为它不是英语大小写,因此应被视为小写的大写字母。
2014年

1
@Neaox,应该是英文的,但这不是首字母缩写大写或normal-english-case;用大写字母分隔。如果源文本的大写方式与普通英语相同,则其他字母也不应该大写。例如,为什么应将“ i”中的“ i”大写以适合大写分隔格式,而不能将“ ANZAC”中的“ NZAC”大写?严格来说,如果您将“ ANZAC”解释为大写分隔符,则它是5个字,每个字母一个。
山姆

19

好的答案,MizardX!我进行了一些微调,将数字视为单独的单词,以便“ AddressLine1”将变为“ Address Line 1”,而不是“ Address Line1”:

Regex.Replace(s, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ")

2
很棒的补充!我怀疑不会有人对接受的答案对字符串中的数字的处理感到惊讶。:)
乔丹·格雷

我知道距您发布此内容已经快8年了,但是它对我来说也非常有效。:)这些数字起初使我震惊。
Michael Armes

通过我的2个异常值测试的唯一答案:“ Take5”->“ Take 5”,“ PublisherID”->“ Publisher ID”。我要对此
投票

18

只是为了一点点变化...这是一个不使用正则表达式的扩展方法。

public static class CamelSpaceExtensions
{
    public static string SpaceCamelCase(this String input)
    {
        return new string(Enumerable.Concat(
            input.Take(1), // No space before initial cap
            InsertSpacesBeforeCaps(input.Skip(1))
        ).ToArray());
    }

    private static IEnumerable<char> InsertSpacesBeforeCaps(IEnumerable<char> input)
    {
        foreach (char c in input)
        {
            if (char.IsUpper(c)) 
            { 
                yield return ' '; 
            }

            yield return c;
        }
    }
}

为了避免使用Trim(),我在foreach之前放了一个:int counter = -1。在里面,添加counter ++。将支票更改为:if(char.IsUpper(c)&& counter> 0)
外包装盒开发人员

这将在第一个字符之前插入一个空格。
Zar Shardan

我已自由解决@ZarShardan指出的问题。如果您不喜欢此更改,请随时回滚或编辑自己的修复程序。
jpmc26

例如,可以通过在一系列大写字母的最后一个大写字母之前添加一个空格来增强缩写以处理缩写,例如BOEForecast => BOE Forecast
Nepaluz

11

除了格兰特·瓦格纳(Grant Wagner)的出色评论:

Dim s As String = RegularExpressions.Regex.Replace("ThisIsMyCapsDelimitedString", "([A-Z])", " $1")

好点……请随意插入您选择的.substring()、. trimstart()、. trim()、. remove()等。:)
伪受虐狂

9

我需要一个支持首字母缩写词和数字的解决方案。此基于Regex的解决方案将以下模式视为单独的“单词”:

  • 大写字母后跟小写字母
  • 连续数字序列
  • 连续的大写字母(解释为首字母缩写词)-一个新单词可以使用最后一个大写字母开始,例如HTMLGuide =>“ HTML Guide”,“ TheATeam” =>“ The A Team”

可以单线执行此操作:

Regex.Replace(value, @"(?<!^)((?<!\d)\d|(?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z]))", " $1")

更具可读性的方法可能会更好:

using System.Text.RegularExpressions;

namespace Demo
{
    public class IntercappedStringHelper
    {
        private static readonly Regex SeparatorRegex;

        static IntercappedStringHelper()
        {
            const string pattern = @"
                (?<!^) # Not start
                (
                    # Digit, not preceded by another digit
                    (?<!\d)\d 
                    |
                    # Upper-case letter, followed by lower-case letter if
                    # preceded by another upper-case letter, e.g. 'G' in HTMLGuide
                    (?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z])
                )";

            var options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled;

            SeparatorRegex = new Regex(pattern, options);
        }

        public static string SeparateWords(string value, string separator = " ")
        {
            return SeparatorRegex.Replace(value, separator + "$1");
        }
    }
}

这是(XUnit)测试的摘录:

[Theory]
[InlineData("PurchaseOrders", "Purchase-Orders")]
[InlineData("purchaseOrders", "purchase-Orders")]
[InlineData("2Unlimited", "2-Unlimited")]
[InlineData("The2Unlimited", "The-2-Unlimited")]
[InlineData("Unlimited2", "Unlimited-2")]
[InlineData("222Unlimited", "222-Unlimited")]
[InlineData("The222Unlimited", "The-222-Unlimited")]
[InlineData("Unlimited222", "Unlimited-222")]
[InlineData("ATeam", "A-Team")]
[InlineData("TheATeam", "The-A-Team")]
[InlineData("TeamA", "Team-A")]
[InlineData("HTMLGuide", "HTML-Guide")]
[InlineData("TheHTMLGuide", "The-HTML-Guide")]
[InlineData("TheGuideToHTML", "The-Guide-To-HTML")]
[InlineData("HTMLGuide5", "HTML-Guide-5")]
[InlineData("TheHTML5Guide", "The-HTML-5-Guide")]
[InlineData("TheGuideToHTML5", "The-Guide-To-HTML-5")]
[InlineData("TheUKAllStars", "The-UK-All-Stars")]
[InlineData("AllStarsUK", "All-Stars-UK")]
[InlineData("UKAllStars", "UK-All-Stars")]

1
+ 1用于解释正则表达式并使之易读。我学到了一些新东西。.NET Regex中有一个自由行距模式和注释。谢谢!
菲利克斯·基尔

4

为了获得更多的变化,使用普通的旧C#对象,以下代码会产生与@MizardX出色的正则表达式相同的输出。

public string FromCamelCase(string camel)
{   // omitted checking camel for null
    StringBuilder sb = new StringBuilder();
    int upperCaseRun = 0;
    foreach (char c in camel)
    {   // append a space only if we're not at the start
        // and we're not already in an all caps string.
        if (char.IsUpper(c))
        {
            if (upperCaseRun == 0 && sb.Length != 0)
            {
                sb.Append(' ');
            }
            upperCaseRun++;
        }
        else if( char.IsLower(c) )
        {
            if (upperCaseRun > 1) //The first new word will also be capitalized.
            {
                sb.Insert(sb.Length - 1, ' ');
            }
            upperCaseRun = 0;
        }
        else
        {
            upperCaseRun = 0;
        }
        sb.Append(c);
    }

    return sb.ToString();
}

2
哇,真丑。现在,我记得为什么我如此热爱正则表达式!+1,但努力。;)
Mark Brackett

3

下面是将以下内容转换为标题大小写的原型:

  • snake_case
  • 骆驼香烟盒
  • PascalCase
  • 句子大小写
  • 标题大小写(保持当前格式)

显然,您自己仅需要“ ToTitleCase”方法。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var examples = new List<string> { 
            "THEQuickBrownFox",
            "theQUICKBrownFox",
            "TheQuickBrownFOX",
            "TheQuickBrownFox",
            "the_quick_brown_fox",
            "theFOX",
            "FOX",
            "QUICK"
        };

        foreach (var example in examples)
        {
            Console.WriteLine(ToTitleCase(example));
        }
    }

    private static string ToTitleCase(string example)
    {
        var fromSnakeCase = example.Replace("_", " ");
        var lowerToUpper = Regex.Replace(fromSnakeCase, @"(\p{Ll})(\p{Lu})", "$1 $2");
        var sentenceCase = Regex.Replace(lowerToUpper, @"(\p{Lu}+)(\p{Lu}\p{Ll})", "$1 $2");
        return new CultureInfo("en-US", false).TextInfo.ToTitleCase(sentenceCase);
    }
}

控制台将如下所示:

THE Quick Brown Fox
The QUICK Brown Fox
The Quick Brown FOX
The Quick Brown Fox
The Quick Brown Fox
The FOX
FOX
QUICK

引用的博客文章


2
string s = "ThisIsMyCapsDelimitedString";
string t = Regex.Replace(s, "([A-Z])", " $1").Substring(1);

我知道会有一种简单的RegEx方式...我必须开始更多地使用它。
Max Schmeling

1
不是正则表达式专家,但是“ HeresAWTFString”会怎样?
尼克

1
您会收到“此处AWTF字符串”,但这正是Matias Nino在问题中所要的。
Max Schmeling

是的,他需要补充一点:“多个相邻的首都不予理会”。在许多情况下,这显然是必需的,例如,这里的“ PublisherID”转到了可怕的“ Publisher
ID

2

正则表达式比简单循环慢约10-12倍:

    public static string CamelCaseToSpaceSeparated(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return str;
        }

        var res = new StringBuilder();

        res.Append(str[0]);
        for (var i = 1; i < str.Length; i++)
        {
            if (char.IsUpper(str[i]))
            {
                res.Append(' ');
            }
            res.Append(str[i]);

        }
        return res.ToString();
    }

1

天真的正则表达式解决方案。将不处理O'Conner,并在字符串的开头也添加一个空格。

s = "ThisIsMyCapsDelimitedString"
split = Regex.Replace(s, "[A-Z0-9]", " $&");

我对您进行了修改,但如果不是以“天真”开头的话,人们通常会更精打细算。
MusiGenesis

我不认为这是一个打击。在这种情况下,天真通常意味着明显或简单(即不一定是最佳解决方案)。没有侮辱的意图。
Ferruccio

0

可能有一个更优雅的解决方案,但这就是我想出的办法:

string myString = "ThisIsMyCapsDelimitedString";

for (int i = 1; i < myString.Length; i++)
{
     if (myString[i].ToString().ToUpper() == myString[i].ToString())
     {
          myString = myString.Insert(i, " ");
          i++;
     }
}

0

尝试使用

"([A-Z]*[^A-Z]*)"

结果将适合带数字的字母混合

Regex.Replace("AbcDefGH123Weh", "([A-Z]*[^A-Z]*)", "$1 ");
Abc Def GH123 Weh  

Regex.Replace("camelCase", "([A-Z]*[^A-Z]*)", "$1 ");
camel Case  

0

从以下位置实现psudo代码:https ://stackoverflow.com/a/5796394/4279201

    private static StringBuilder camelCaseToRegular(string i_String)
    {
        StringBuilder output = new StringBuilder();
        int i = 0;
        foreach (char character in i_String)
        {
            if (character <= 'Z' && character >= 'A' && i > 0)
            {
                output.Append(" ");
            }
            output.Append(character);
            i++;
        }
        return output;
    }


0

程序和快速暗示:

  /// <summary>
  /// Get the words in a code <paramref name="identifier"/>.
  /// </summary>
  /// <param name="identifier">The code <paramref name="identifier"/></param> to extract words from.
  public static string[] GetWords(this string identifier) {
     Contract.Ensures(Contract.Result<string[]>() != null, "returned array of string is not null but can be empty");
     if (identifier == null) { return new string[0]; }
     if (identifier.Length == 0) { return new string[0]; }

     const int MIN_WORD_LENGTH = 2;  //  Ignore one letter or one digit words

     var length = identifier.Length;
     var list = new List<string>(1 + length/2); // Set capacity, not possible more words since we discard one char words
     var sb = new StringBuilder();
     CharKind cKindCurrent = GetCharKind(identifier[0]); // length is not zero here
     CharKind cKindNext = length == 1 ? CharKind.End : GetCharKind(identifier[1]);

     for (var i = 0; i < length; i++) {
        var c = identifier[i];
        CharKind cKindNextNext = (i >= length - 2) ? CharKind.End : GetCharKind(identifier[i + 2]);

        // Process cKindCurrent
        switch (cKindCurrent) {
           case CharKind.Digit:
           case CharKind.LowerCaseLetter:
              sb.Append(c); // Append digit or lowerCaseLetter to sb
              if (cKindNext == CharKind.UpperCaseLetter) {
                 goto TURN_SB_INTO_WORD; // Finish word if next char is upper
              }
              goto CHAR_PROCESSED;
           case CharKind.Other:
              goto TURN_SB_INTO_WORD;
           default:  // charCurrent is never Start or End
              Debug.Assert(cKindCurrent == CharKind.UpperCaseLetter);
              break;
        }

        // Here cKindCurrent is UpperCaseLetter
        // Append UpperCaseLetter to sb anyway
        sb.Append(c); 

        switch (cKindNext) {
           default:
              goto CHAR_PROCESSED;

           case CharKind.UpperCaseLetter: 
              //  "SimpleHTTPServer"  when we are at 'P' we need to see that NextNext is 'e' to get the word!
              if (cKindNextNext == CharKind.LowerCaseLetter) {
                 goto TURN_SB_INTO_WORD;
              }
              goto CHAR_PROCESSED;

           case CharKind.End:
           case CharKind.Other:
              break; // goto TURN_SB_INTO_WORD;
        }

        //------------------------------------------------

     TURN_SB_INTO_WORD:
        string word = sb.ToString();
        sb.Length = 0;
        if (word.Length >= MIN_WORD_LENGTH) {  
           list.Add(word);
        }

     CHAR_PROCESSED:
        // Shift left for next iteration!
        cKindCurrent = cKindNext;
        cKindNext = cKindNextNext;
     }

     string lastWord = sb.ToString();
     if (lastWord.Length >= MIN_WORD_LENGTH) {
        list.Add(lastWord);
     }
     return list.ToArray();
  }
  private static CharKind GetCharKind(char c) {
     if (char.IsDigit(c)) { return CharKind.Digit; }
     if (char.IsLetter(c)) {
        if (char.IsUpper(c)) { return CharKind.UpperCaseLetter; }
        Debug.Assert(char.IsLower(c));
        return CharKind.LowerCaseLetter;
     }
     return CharKind.Other;
  }
  enum CharKind {
     End, // For end of string
     Digit,
     UpperCaseLetter,
     LowerCaseLetter,
     Other
  }

测试:

  [TestCase((string)null, "")]
  [TestCase("", "")]

  // Ignore one letter or one digit words
  [TestCase("A", "")]
  [TestCase("4", "")]
  [TestCase("_", "")]
  [TestCase("Word_m_Field", "Word Field")]
  [TestCase("Word_4_Field", "Word Field")]

  [TestCase("a4", "a4")]
  [TestCase("ABC", "ABC")]
  [TestCase("abc", "abc")]
  [TestCase("AbCd", "Ab Cd")]
  [TestCase("AbcCde", "Abc Cde")]
  [TestCase("ABCCde", "ABC Cde")]

  [TestCase("Abc42Cde", "Abc42 Cde")]
  [TestCase("Abc42cde", "Abc42cde")]
  [TestCase("ABC42Cde", "ABC42 Cde")]
  [TestCase("42ABC", "42 ABC")]
  [TestCase("42abc", "42abc")]

  [TestCase("abc_cde", "abc cde")]
  [TestCase("Abc_Cde", "Abc Cde")]
  [TestCase("_Abc__Cde_", "Abc Cde")]
  [TestCase("ABC_CDE_FGH", "ABC CDE FGH")]
  [TestCase("ABC CDE FGH", "ABC CDE FGH")] // Should not happend (white char) anything that is not a letter/digit/'_' is considered as a separator
  [TestCase("ABC,CDE;FGH", "ABC CDE FGH")] // Should not happend (,;) anything that is not a letter/digit/'_' is considered as a separator
  [TestCase("abc<cde", "abc cde")]
  [TestCase("abc<>cde", "abc cde")]
  [TestCase("abc<D>cde", "abc cde")]  // Ignore one letter or one digit words
  [TestCase("abc<Da>cde", "abc Da cde")]
  [TestCase("abc<cde>", "abc cde")]

  [TestCase("SimpleHTTPServer", "Simple HTTP Server")]
  [TestCase("SimpleHTTPS2erver", "Simple HTTPS2erver")]
  [TestCase("camelCase", "camel Case")]
  [TestCase("m_Field", "Field")]
  [TestCase("mm_Field", "mm Field")]
  public void Test_GetWords(string identifier, string expectedWordsStr) {
     var expectedWords = expectedWordsStr.Split(' ');
     if (identifier == null || identifier.Length <= 1) {
        expectedWords = new string[0];
     }

     var words = identifier.GetWords();
     Assert.IsTrue(words.SequenceEqual(expectedWords));
  }

0

一个简单的解决方案,应该比正则表达式解决方案快几个数量级(基于我针对该线程的顶级解决方案进行的测试),尤其是随着输入字符串大小的增长:

string s1 = "ThisIsATestStringAbcDefGhiJklMnoPqrStuVwxYz";
string s2;
StringBuilder sb = new StringBuilder();

foreach (char c in s1)
    sb.Append(char.IsUpper(c)
        ? " " + c.ToString()
        : c.ToString());

s2 = sb.ToString();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.