有没有一种优雅的方式来解析一个单词,并添加之前大写字母空间 [英] is there a elegant way to parse a word and add spaces before capital letters

查看:230
本文介绍了有没有一种优雅的方式来解析一个单词,并添加之前大写字母空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 do I convert CamelCase into human-readable names in Java?
  • How does the regular expression (?<=#)[^#]+(?=#) work?
  • <一个href="http://www.regular-ex$p$pssions.info/lookaround.html">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
        • 这篇关于有没有一种优雅的方式来解析一个单词,并添加之前大写字母空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆