Tor*_*man 6 .net regex pascalcasing c#-4.0
我正在使用 ReSharper 并试图遵守它的默认规则。
在我的部分代码中,我需要将字符串属性更改为 PascalCase。
我尝试了多种方法,但找不到一种适用于所有大写缩写的方法。
前任:
MPSUser --> Still MPSUser (should be MpsUser)
ArticleID --> Still Article ID (Should be ArticleId)
closeMethod --> Works and changes to CloseMethod
Run Code Online (Sandbox Code Playgroud)
谁能帮我创建一个可以将任何字符串转换为 PascalCase 的方法?谢谢!
我所知道的唯一转换为 的内置方法PascalCase是TextInfo.ToTitleCase,并且它在设计上不处理全大写单词。为了解决这个问题,我制作了一个自定义正则表达式,可以检测所有单词部分,然后将它们单独转换为标题/帕斯卡大小写:
string ToPascalCase(string s)
{
// Find word parts using the following rules:
// 1. all lowercase starting at the beginning is a word
// 2. all caps is a word.
// 3. first letter caps, followed by all lowercase is a word
// 4. the entire string must decompose into words according to 1,2,3.
// Note that 2&3 together ensure MPSUser is parsed as "MPS" + "User".
var m = Regex.Match(s, "^(?<word>^[a-z]+|[A-Z]+|[A-Z][a-z]+)+$");
var g = m.Groups["word"];
// Take each word and convert individually to TitleCase
// to generate the final output. Note the use of ToLower
// before ToTitleCase because all caps is treated as an abbreviation.
var t = Thread.CurrentThread.CurrentCulture.TextInfo;
var sb = new StringBuilder();
foreach (var c in g.Captures.Cast<Capture>())
sb.Append(t.ToTitleCase(c.Value.ToLower()));
return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
该函数应该处理常见用例:
s | ToPascalCase(s)
MPSUser | MpsUser
ArticleID | ArticleId
closeMethod | CloseMethod
Run Code Online (Sandbox Code Playgroud)