Change caseing

kejpa

Well-known member
Joined
Oct 10, 2003
Messages
320
Hi,
Id like to search for a string case insensitive and if found change it to the way its written in the pattern. Simple enough, but how?

Consider the pattern to be "\b(Me|MySelf|I|Kejpa)\b".

TIA
/Kejpa
 
In all honesty, I dont really know much of anything about regular expressions, except what I learned while looking for this answer. My guess is that you should do a case-insensitive replace, where matches are effectively replaced with the pattern they matched. I dont think this is exactly what you want, but it is a start. The secret would be RegexOptions.IgnoreCase.

[VB]
Import the RegularExpressions namespace
Result = Regex.Replace("I want me to be capitalized", "\bMe\b", " Me ", RegexOptions.IgnoreCase)
Result = "I want Me to be capitalized"
[/VB]

Also, I found this in the help (ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfSystemTextRegularExpressionsRegexClassReplaceTopic.htm). I think it would probably suit your needs better than any code I wrote for regular expressions.


[VB]
Imports System.Text.RegularExpressions

Class RegExSample
Shared Function CapText(m As Match) As String
Get the matched string.
Dim x As String = m.ToString()
If the first char is lower case...
If Char.IsLower(x.Chars(0)) Then
Capitalize it.
Return Char.ToUpper(x.Chars(0)) + x.Substring(1, x.Length - 1)
End If
Return x
End Function

Public Shared Sub Main()
Dim text As String = "four score and seven years ago"
System.Console.WriteLine("text=[" + text + "]")
Dim result As String = Regex.Replace(text, "\w+", _
AddressOf RegExSample.CapText)
System.Console.WriteLine("result=[" + result + "]")
End Sub
End Class
[/VB]
 
marble_eater said:
The secret would be RegexOptions.IgnoreCase.

[VB]
Import the RegularExpressions namespace
Result = Regex.Replace("I want me to be capitalized", "\bMe\b", " Me ", RegexOptions.IgnoreCase)
Result = "I want Me to be capitalized"
[/VB]
Sooo simple, and soo very not flexible and scaleable.

What I like is to mimic whats happening in VB.NET IDE, if you write "elseif" you will get "ElseIf" when you have finished the word with a white space char or some other char (\W)
Should I use Regex for changing
"i want to capitalize myselft" to
"I want to capitalize MySelf"
or am I better off with find loops?

TIA
/Kejpa
 
Back
Top