有没有一种优雅的方式来解析一个单词,并添加之前大写字母空间大写字母、单词、优雅、方式

2023-09-02 01:35:39 作者:青春荒唐我不负她*

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

i need to parse some data and i want to convert

AutomaticTrackingSystem

Automatic Tracking System

基本上是把一个空间的任何大写字母之前(当然除了第一个)

essentially putting a space before any capital letter (besides the first one of course)

推荐答案

您可以使用lookarounds,例如:

You can use lookarounds, e.g:

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

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

此照片(因为看到ideone.com ):

Automatic Tracking System
X M L Editor

正则表达式(^!)由两个断言(= [AZ]?):

The regex (?!^)(?=[A-Z]) consists of two assertions:

(^!) - 也就是我们不是在字符串的开始 (= [AZ]) - 即我们只是一个大写字母之前 (?!^) - i.e. we're not at the beginning of the string (?=[A-Z]) - i.e. we're just before an uppercase letter How我做驼峰转换成Java的人类可读的名字? 如何经常EX pression (小于?=#)[^#] + 工作 (=#?)? How do I convert CamelCase into human-readable names in Java? How does the regular expression (?<=#)[^#]+(?=#) work? regular-ex$p$pssions.info/Lookarounds

在此处,使用断言真正有所作为,当你有几个不同的规则,和/或要分割而不是替换。这个例子结合了:

Here's where using assertions really make a difference, when you have several different rules, and/or you want to Split instead of Replace. This example combines both:

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();
}

此照片(因为看到ideone.com ):

[Automatic][Tracking][System]
[XML][Editor]
[An][XML][And][XSLT][2.0][Tool]

相关问题

的Java分裂是吃了我的角色。 在对零宽度匹配断言分裂的例子很多

Related questions

Java split is eating my characters. Has many examples of splitting on zero-width matching assertions