【发布时间】:2018-06-11 04:17:20
【问题描述】:
我正在编写一个方便的小扩展方法,它将接受一个字符串并将其返回格式,就好像它是一个 lowerCamelCase JSON 标识符一样。
这是我目前所拥有的......请问我可以帮助改进它吗?
我需要以下行为:
- 用户名 => 用户名
- 用户 ID => 用户 ID
- 用户 => 用户
- 钓鱼之旅 => 钓鱼之旅
- 123123123 => 123123123
- aaa123 => aaa123
- 你好,这就是我 => helloWorldThisIsMe
奖励 - 如果我们能以某种方式去除非 [A-Za-z0-9] 字符?我想我可以再做一轮正则表达式?
感谢您的帮助!
public static string ToJsonIdentifier(string s)
{
// special case, s is empty
if (string.IsNullOrEmpty(s)) return s;
// clean up the string, remove any non-standard chars
s = Regex.Replace(s, @"[^A-Za-z0-9\s]+", "");
// special case s is whitespace
if (string.IsNullOrWhiteSpace(s)) return String.Empty;
// special case s is only 1 letter
if (!string.IsNullOrEmpty(s) && s.Length == 1)
return s.ToLowerInvariant();
// detect word boundaries where the case changes and add whitespace there, so the next code splits it up
s = Regex.Replace(s, "([a-z])([A-Z])", m=> m.Groups[1].Value + " " + m.Groups[2].Value);
// multiple words, so for each whitespace separated bit, uppercase the first letter, and deal with special cases
if (s.Contains(" "))
{
s = string.Join("", s.Split(' ').ToList().Select(z =>
{
if (string.IsNullOrWhiteSpace(z)) return string.Empty;
if (z.Length == 1) return z.ToUpperInvariant();
return z.ToUpperInvariant()
.Substring(0, 1) + z.Substring(1).ToLowerInvariant();
}));
}
// lowercase the first letter
return char.ToLower(s[0]) + s.Substring(1);
}
研究:我看过这些问题,似乎相关:
我正在进行的尝试:https://dotnetfiddle.net/PR31Hl
【问题讨论】:
-
你能显示你的 json 并且是 's' 指定你的 json 字符串吗?
-
这是一个扩展方法,所以你可以在任何字符串上调用它。我已经添加了我所期望的行为,请你解释一下你需要什么?