Regex For Finding Ctypes with Int32
        Posted  
        
            by 
                Stefan H
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Stefan H
        
        
        
        Published on 2010-12-22T17:55:25Z
        Indexed on 
            2010/12/22
            19:54 UTC
        
        
        Read the original article
        Hit count: 480
        
(Hey all,
I am looking for a little regex help...
I am trying to find all CType(expression,Int32) s and replace them with CInt(expression)
This, however, is proving quite difficult, considering there could be a nested Ctype(expression, Int32) within the regex match. Does anyone have any ideas for how to best go about doing this?
Here is what I have now:
Dim str As String = "CType((original.Width * CType((targetSize / CType(original.Height, Single)), Single)), Int32)"
Dim exp As New Regex("CType\((.+), Int32\)")
str = exp.Replace(str, "CInt($1)")
But this will match the entire string and replace it.
I was thinking of doing a recursive function to find the outer most match, and then work inwards, but that still presents a problem with things like
CType(replaceChars(I), Int32)), Chr(CType(replacementChars(I), Int32)
Any tips would be appreciated.
Input
returnString.Replace(Chr(CType(replaceChars(I), Int32)), Chr(CType(replacementChars(I), Int32)))
Output:
 returnString.Replace(Chr(CInt(replaceChars(I))),Chr(CInt(replacementChars(I))))
Edit:
Been working on it a little more and have a recursive function that I'm still working out the kinks in. Recursion + regex. it kinda hurts.
 Private Function FindReplaceCInts(ByVal strAs As String) As String
    System.Console.WriteLine(String.Format("Testing : {0}", strAs))
    Dim exp As New Regex("CType\((.+), Int32\)")
    If exp.Match(strAs).Success Then
        For Each match As Match In exp.Matches(strAs)
            If exp.Match(match.Value.Substring(2)).Success Then
                Dim replaceT As String = match.Value.Substring(2)
                Dim Witht As String = FindReplaceCInts(match.Value.Substring(2))
                System.Console.WriteLine(strAs.IndexOf(replaceT))
                strAs.Replace(replaceT, Witht)
            End If
        Next
        strAs = exp.Replace(strAs, "CInt($1)")
    End If
    Return strAs
End Function
Cheers,
© Stack Overflow or respective owner