是否可以使用正则表达式将每个单词的第一个字符大写?
我将在VB.net(SSIS)中使用它
为什么不使用.NET Framework中已有的内置TextInfo.ToTitleCase()方法?
string capitalized = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("this string should be capitalized!");
编辑:下面添加的VB.NET代码
Dim input As String = "The quick brown fox jumps over the lazy dog" Dim pattern As String = "\b(\w|['-])+\b" ' With lambda support: Dim result As String = Regex.Replace(input, pattern, _ Function (m) m.Value(0).ToString().ToUpper() & m.Value.Substring(1))
如果你不能使用lambdas,那么使用MatchEvaluator代替:
Dim evaluator As MatchEvaluator = AddressOf TitleCase Dim result As String = Regex.Replace(input, pattern, evaluator) Public Function TitleCase(ByVal m As Match) As String Return m.Value(0).ToString().ToUpper() & m.Value.Substring(1) End Function
从MS Word格式的意义上说,它不是真正的标题案例,但足够接近.
string input = "The quick brown fox jumps over the lazy dog"; string pattern = @"\b(\w|['-])+\b"; string result = Regex.Replace(input, pattern, m => m.Value[0].ToString().ToUpper() + m.Value.Substring(1));
这很好地处理一个字母单词,因为Substring不会在输入中的"A"之类的东西上抛出错误.
.NET内置了对此的支持.有关文档,请参见TextInfo.ToTitleCase.
我的代码包含一些C#的扩展方法.我假设VB.NET也有这些,但我不太了解VB.NET自己转换它们.
public static class StringExtensions { public static string ToTitleCase(this string value) { return value.ToTitleCase(CultureInfo.InvariantCulture); } public static string ToTitleCase(this string value, CultureInfo culture) { return value.ToTitleCase(culture.TextInfo); } public static string ToTitleCase(this string value, TextInfo textInfo) { return textInfo.ToTitleCase(value); } }
Dim s As String = "your string" Dim s2 As String = StrConv(s, VbStrConv.ProperCase MessageBox.Show(s2)