Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

  • Leaders
Posted

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

[sIGPIC]e[/sIGPIC]
Posted
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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...