我正在寻找一种方法将PascalCase字符串(例如"MyString")拆分为单独的单词 - "My","String".另一个用户提出了这个问题bash,但我想知道如何使用常规正则表达式或至少在.NET中.
如果你能找到一种方法来分割(并且可选地大写)camelCase字符串:例如,"myString"变成"my"和"String",可以选择大写/小写字符串中的一个或两个.
chi*_*emp 14
看到这个问题:是否有一种优雅的方法来解析单词并在大写字母之前添加空格? 它接受的答案涵盖了你想要的内容,包括连续的数字和几个大写字母.虽然此示例包含以大写字母开头的单词,但当第一个单词为小写时,它同样有效.
string[] tests = {
"AutomaticTrackingSystem",
"XMLEditor",
"AnXMLAndXSLT2.0Tool",
};
Regex r = new Regex(
@"(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])"
);
foreach (string s in tests)
r.Replace(s, " ");
Run Code Online (Sandbox Code Playgroud)
以上将输出:
[Automatic][Tracking][System]
[XML][Editor]
[An][XML][And][XSLT][2.0][Tool]
Run Code Online (Sandbox Code Playgroud)
And*_*ose 10
只是提供RegEx和循环解决方案的替代方案,这里提供的所有内容都是使用LINQ的答案,LINQ也处理驼峰案例和首字母缩略词:
string[] testCollection = new string[] { "AutomaticTrackingSystem", "XSLT", "aCamelCaseWord" };
foreach (string test in testCollection)
{
// if it is not the first character and it is uppercase
// and the previous character is not uppercase then insert a space
var result = test.SelectMany((c, i) => i != 0 && char.IsUpper(c) && !char.IsUpper(test[i - 1]) ? new char[] { ' ', c } : new char[] { c });
Console.WriteLine(new String(result.ToArray()));
}
Run Code Online (Sandbox Code Playgroud)
这个输出是:
Automatic Tracking System
XSLT
a Camel Case Word
Run Code Online (Sandbox Code Playgroud)
void Main()
{
"aCamelCaseWord".ToFriendlyCase().Dump();
}
public static class Extensions
{
public static string ToFriendlyCase(this string PascalString)
{
return Regex.Replace(PascalString, "(?!^)([A-Z])", " $1");
}
}
Run Code Online (Sandbox Code Playgroud)
输出a Camel Case Word(.Dump()只打印到控制台).
| 归档时间: |
|
| 查看次数: |
4370 次 |
| 最近记录: |