kejpa Posted March 16, 2005 Posted March 16, 2005 Hi, I'd like to search for a string case insensitive and if found change it to the way it's written in the pattern. Simple enough, but how? Consider the pattern to be "\b(Me|MySelf|I|Kejpa)\b". TIA /Kejpa Quote
Leaders snarfblam Posted March 16, 2005 Leaders Posted March 16, 2005 In all honesty, I don't 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 don't think this is exactly what you want, but it is a start. The secret would be RegexOptions.IgnoreCase. '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" 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. 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 Quote [sIGPIC]e[/sIGPIC]
HJB417 Posted March 16, 2005 Posted March 16, 2005 If you want to use regex, you'll probably need to use the match evalutor. Quote
Leaders snarfblam Posted March 16, 2005 Leaders Posted March 16, 2005 (Thats exactly what my second example does) Quote [sIGPIC]e[/sIGPIC]
kejpa Posted March 17, 2005 Author Posted March 17, 2005 The secret would be RegexOptions.IgnoreCase. '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" Sooo simple, and soo very not flexible and scaleable. What I like is to mimic what's 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 Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.