我正在使用ReSharper并尝试遵守它的默认规则。
在我的部分代码中,我需要将字符串Property更改为PascalCase。
我尝试了很多方法,但找不到适用于包含所有大写缩写词的内容的方法。
EX:
MPSUser --> Still MPSUser (should be MpsUser)
ArticleID --> Still Article ID (Should be ArticleId)
closeMethod --> Works and changes to CloseMethod
任何人都可以帮我创建一个可以将任何String转换为PascalCase的方法吗? 谢谢!
答案 0 :(得分:4)
我知道转换为PascalCase
的唯一内置方法是TextInfo.ToTitleCase
,并且它不会按设计处理全部大写字词。为了解决这个问题,我制作了一个可以检测所有单词部分的自定义正则表达式,然后将它们单独转换为Title / Pascal Case:
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();
}
此函数应处理常见用例:
s | ToPascalCase(s)
MPSUser | MpsUser
ArticleID | ArticleId
closeMethod | CloseMethod
答案 1 :(得分:2)
我从mellamokb的解决方案中大量借用了一些更全面的东西。例如,我想留下数字。另外,我希望将任何非字母,非数字字符用作分隔符。这是:
public static string ToPascalCase(this string s) {
var result = new StringBuilder();
var nonWordChars = new Regex(@"[^a-zA-Z0-9]+");
var tokens = nonWordChars.Split(s);
foreach (var token in tokens) {
result.Append(PascalCaseSingleWord(token));
}
return result.ToString();
}
static string PascalCaseSingleWord(string s) {
var match = Regex.Match(s, @"^(?<word>\d+|^[a-z]+|[A-Z]+|[A-Z][a-z]+|\d[a-z]+)+$");
var groups = match.Groups["word"];
var textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;
var result = new StringBuilder();
foreach (var capture in groups.Captures.Cast<Capture>()) {
result.Append(textInfo.ToTitleCase(capture.Value.ToLower()));
}
return result.ToString();
}
这是一个x-unit测试,显示了一些测试用例:
[Theory]
[InlineData("imAString", "ImAString")]
[InlineData("imAlsoString", "ImAlsoString")]
[InlineData("ImAlsoString", "ImAlsoString")]
[InlineData("im_a_string", "ImAString")]
[InlineData("im a string", "ImAString")]
[InlineData("ABCAcronym", "AbcAcronym")]
[InlineData("im_a_ABCAcronym", "ImAAbcAcronym")]
[InlineData("im a ABCAcronym", "ImAAbcAcronym")]
[InlineData("8ball", "8Ball")]
[InlineData("im a 8ball", "ImA8Ball")]
[InlineData("IM_ALL_CAPS", "ImAllCaps")]
[InlineData("IM ALSO ALL CAPS", "ImAlsoAllCaps")]
[InlineData("i-have-dashes", "IHaveDashes")]
[InlineData("a8word_another_word", "A8WordAnotherWord")]
public void WhenGivenString_ShouldPascalCaseIt(string input, string expectedResult) {
var result = input.ToPascalCase();
Assert.Equal(expectedResult, result);
}