我正在尝试找出一种使用 toTitleCase 来忽略序数的方法。它按照我希望的方式适用于除序数之外的所有字符串(例如,1st、2nd、3rd 变为 1St、2Nd、3Rd)。
如有任何帮助,我们将不胜感激。正则表达式可能是处理这个问题的方法,我只是不确定如何构造这样的正则表达式。
更新:这是我使用的解决方案(使用我在下面的扩展方法中编写的约翰的答案):
public static string ToTitleCaseIgnoreOrdinals(this string text)
{
string input = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
string result = System.Text.RegularExpressions.Regex.Replace(input, "([0-9]st)|([0-9]th)|([0-9]rd)|([0-9]nd)", new System.Text.RegularExpressions.MatchEvaluator((m) => m.Captures[0].Value.ToLower()), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return result;
}
最佳答案
string input = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello there, this is the 1st");
string result = System.Text.RegularExpressions.Regex.Replace(input, "([0-9]st)|([0-9]th)|([0-9]rd)|([0-9]nd)", new System.Text.RegularExpressions.MatchEvaluator((m) =>
{
return m.Captures[0].Value.ToLower();
}), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
关于c# - toTitleCase 忽略 C# 中的序数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168617/