您可以使用环视,例如:
string[] tests = {
"AutomaticTrackingSystem",
"XMLEditor",
};
Regex r = new Regex(@"(?!^)(?=[A-Z])");
foreach (string test in tests) {
Console.WriteLine(r.Replace(test, " "));
}
这打印(如 ideone.com 上所示 http://ideone.com/5b0G2):
Automatic Tracking System
X M L Editor
正则表达式(?!^)(?=[A-Z])
由两个断言组成:
-
(?!^)
- 即我们不在字符串的开头
-
(?=[A-Z])
- 即我们就在大写字母之前
相关问题
- 如何在 Java 中将 CamelCase 转换为人类可读的名称? https://stackoverflow.com/questions/2559759/how-do-i-convert-camelcase-into-human-readable-names-in-java/
- 正则表达式是如何实现的(?<=#)[^#]+(?=#) work? https://stackoverflow.com/questions/3092797/how-does-the-regular-expression-work/
参考
- 正则表达式.info/Lookarounds http://www.regular-expressions.info/lookaround.html
平分差价
当您有多个不同的规则和/或您想要时,使用断言确实会产生影响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();
}
这打印(如 ideone.com 上所示 http://ideone.com/Qw5iC):
[Automatic][Tracking][System]
[XML][Editor]
[An][XML][And][XSLT][2.0][Tool]
相关问题
-
Java split is eating my characters. https://stackoverflow.com/questions/2819933/java-split-is-eating-my-characters/