How to uppercase the first character of each word using a regex in VB.NET?

前端 未结 9 1479
無奈伤痛
無奈伤痛 2020-12-06 19:19

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

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

相关标签:
9条回答
  • 2020-12-06 19:23

    Use ProperCase function:

    Dim Str As String = "the quick brown fox jumps over the lazy dog"
    Dim NewStr As String = StrConv(Str, VbStrConv.ProperCase) 
    

              

    0 讨论(0)
  • 2020-12-06 19:25
    Dim s As String = "your string"
    Dim s2 As String = StrConv(s, VbStrConv.ProperCase
    MessageBox.Show(s2)
    
    0 讨论(0)
  • 2020-12-06 19:26

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

    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
    

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


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

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

    0 讨论(0)
  • 2020-12-06 19:32

    Not in "pure" regex, but most platform-specific implementations have a way to do it:

    For example, in python:

    import re
    re.compile(r'\b\w').sub(lambda x: x.group(0).upper(), 'hello')
    

    In this case we pass a callable lambda to the sub() method (rather than a replacement string) that will return the matching string upper cased. Most languages have some equivalent where you pass a callable as the 'replacement'.

    In VB.NET you can pass your 'replacement' lambda as Function (x) x.Value(0).ToString().ToUpper()

    0 讨论(0)
  • 2020-12-06 19:32

    Do this on key press event of your text box.

    If e.KeyChar <> ChrW(Keys.Back) Then
                If txtEname.Text = "" Then
                    e.KeyChar = UCase(e.KeyChar)
                End If
    
    
            End If
    
    0 讨论(0)
  • 2020-12-06 19:40

    You could do that, however this is a pretty common function in most programming languages. For example, the function is ucwords($word) in PHP.

    0 讨论(0)
提交回复
热议问题