Is it possible to uppercase the first character of each word using regex?
I\'m going to be using this in VB.net (SSIS)
Use ProperCase
function:
Dim Str As String = "the quick brown fox jumps over the lazy dog"
Dim NewStr As String = StrConv(Str, VbStrConv.ProperCase)
Dim s As String = "your string"
Dim s2 As String = StrConv(s, VbStrConv.ProperCase
MessageBox.Show(s2)
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.
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.
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()
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
You could do that, however this is a pretty common function in most programming languages. For example, the function is ucwords($word) in PHP.