是否有一种优雅的方法来解析单词并在大写字母之前添加空格

leo*_*ora 19 .net c# regex

我需要解析一些数据,我想转换

AutomaticTrackingSystem
Run Code Online (Sandbox Code Playgroud)

Automatic Tracking System
Run Code Online (Sandbox Code Playgroud)

基本上在任何大写字母之前放置一个空格(当然除了第一个)

pol*_*nts 26

您可以使用外观,例如:

string[] tests = {
   "AutomaticTrackingSystem",
   "XMLEditor",
};

Regex r = new Regex(@"(?!^)(?=[A-Z])");
foreach (string test in tests) {
   Console.WriteLine(r.Replace(test, " "));
}
Run Code Online (Sandbox Code Playgroud)

打印(如ideone.com上所示):

Automatic Tracking System
X M L Editor
Run Code Online (Sandbox Code Playgroud)

正则表达式(?!^)(?=[A-Z])由两个断言组成:

  • (?!^) - 即我们不在字符串的开头
  • (?=[A-Z]) - 即我们就在大写字母之前

相关问题

参考


分裂差异

当你有几个不同的规则,和/或你想要Split代替时,使用断言确实有所作为Replace.这个例子结合了两个:

string[] tests = {
   "AutomaticTrackingSystem",
   "XMLEditor",
   "AnXMLAndXSLT2.0Tool",
};

Regex r = new Regex(
   @"  (?<=[A-Z])(?=[A-Z][a-z])    # UC before me, UC lc after me
    |  (?<=[^A-Z])(?=[A-Z])        # Not UC before me, UC after me
    |  (?<=[A-Za-z])(?=[^A-Za-z])  # Letter before me, non letter after me
    ",
   RegexOptions.IgnorePatternWhitespace
);
foreach (string test in tests) {
   foreach (string part in r.Split(test)) {
      Console.Write("[" + part + "]");
   }
   Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)

打印(如ideone.com上所示):

[Automatic][Tracking][System]
[XML][Editor]
[An][XML][And][XSLT][2.0][Tool]
Run Code Online (Sandbox Code Playgroud)

相关问题


小智 19

没有正则表达式,你可以做类似的事情(或者使用LINQ更简洁的东西):

(注意:没有错误检查,你应该添加它)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {
            String test = "AStringInCamelCase";
            StringBuilder sb = new StringBuilder();

            foreach (char c in test)
            {
                if (Char.IsUpper(c))
                {
                    sb.Append(" ");
                }
                sb.Append(c);
            }

            if (test != null && test.Length > 0 && Char.IsUpper(test[0]))
            {
                sb.Remove(0, 1);
            }

            String result = sb.ToString();
            Console.WriteLine(result);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这给出了输出

A String In Camel Case
Run Code Online (Sandbox Code Playgroud)

  • +1用于实现合理且可读的解决方案,而不是盲目地使用正则表达式. (4认同)