Normal Casing of an Upper Case Paragraph Using .NET Regular Expressions






2.23/5 (5 votes)
Mar 13, 2007

45363

177
Illustrates a method of taking a multi-sentence string that is in all caps, and converting to to normal case.
Introduction
Use regular expression engine in .NET to convert a multi-sentence string to normal case.
Background
Many developers use data from legacy systems that generate strings that are all upper case. Sometimes you may need an efficient way to display those lengthy strings in correct case where the first letter of every sentence is capitalized and the rest is lower case.
Using the code
The code is simple and does work but its not perfect. Proper nouns such as names of places and people will not be correct cased, and I dont know of a way to recognize them all in code. But this methodology seems to work in cases where proper nouns are not an issue.
The example is a console application in VB.NET. It's fairly well documented and I think most developers will not have a problem using it. I'd welcome any help to improve the regular expression pattern and if anybody knows of a way to recognize proper nouns in code - I'd love to see it.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
'This is a way you can take an upper case sentence
'and convert it to proper case. This example uses
'the .NET Regular Expressions engine for efficient
'text pattern searching. It then uses a delegate method that is
'called by the RegEx engine everytime it finds a match. The delegate
'method merely uppercases the matched text.
'UPPER CASE MESSAGE FROM A LEGACY SYSTEM
Dim ORGmSG As String = "I HOPE THIS WORKS FOR ALL SITUATIONS. " & _
"BUT ITS LIKELY THAT YOU MAY FIND A BUG. IF YOU DO THEN LET ME KNOW. " & _
vbCrLf & vbCrLf & "NOW IS THE TIME, FOR ALL GOOD MEN, TO COME TO THE AID " & _
"OF THEIR COUNTRY."
'create an immutable regular expression object with its pattern set
Dim reg As New Regex("^[a-z]|\b\. [a-z0-9]?| i ", RegexOptions.Multiline)
'convert the upper case string to all lower, ask regex engine to
'do a replace on it with the delegate method I called eval().
Console.WriteLine(reg.Replace(ORGmSG.ToLower, AddressOf eval))
Console.ReadKey()
End Sub
Private Function eval(ByVal m As Match) As String
Return m.ToString.ToUpper()
End Function
End Module
History
3-12-2007 Initial code review.