如何在 VB.NET 中使用正则表达式将每个单词的第一个字符大写? [英] How to uppercase the first character of each word using a regex in VB.NET?

查看:52
本文介绍了如何在 VB.NET 中使用正则表达式将每个单词的第一个字符大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用正则表达式将每个单词的第一个字符大写?

Is it possible to uppercase the first character of each word using regex?

我将在 VB.net (SSIS) 中使用它

I'm going to be using this in VB.net (SSIS)

推荐答案

VB.NET 代码添加到下面

VB.NET code added below

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))

如果您不能使用 lambda,请改用 MatchEvaluator:

If you can't use lambdas then use a MatchEvaluator instead:

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 格式而言,这不是真正的标题大小写,但足够接近.

It's not really Title case in the sense of the MS Word formatting, but close enough.

<小时>您没有指定语言,但在 C# 中您可以这样做:


You didn't specify the language, but in C# you could do this:

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"之类的东西上抛出错误.

This nicely handles one letter words, as Substring won't throw an error on something such as "A" in the input.

这篇关于如何在 VB.NET 中使用正则表达式将每个单词的第一个字符大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆