need help with regular expression

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mikekimhome@gmail.com

    #1

    need help with regular expression

    I am trying to capture a whole function definition from a file. I have
    read the contents of the file into a string variable and tried a regex
    to extract the function definition. Good thing is I already know the
    function signature. For example, i have a string
    variable(sFileC ontents) that holds the following contents and I already
    know what I am looking for is function body for "function Foo(byval a
    as integer)"

    ---- start of the content---------

    Dim objRS, SQL
    Dim sChannel


    function Foo(byval a as integer)
    ' do something
    dim c as integer

    if a > 0 then
    exit function
    c = a + a
    Foo = c
    end function

    ' something else .....


    ---- end of the content---------


    I tried the following but no avail. please help!!

    Dim oRegex As Regex
    Dim oMatch As Match

    oRegex = New Regex((?<result >(function Foo\(byval a as
    integer\))(\w+) function$), RegexOptions.Ig noreCase Or
    RegexOptions.Co mpiled)
    oMatch = oRegex.Match(sF ileContents)


    If oMatch.Success Then
    sFuncBody = oMatch.Groups(" result").ToStri ng()
    End If

  • Cerebrus

    #2
    Re: need help with regular expression

    Hi Mike,

    Since you just need the part between (and including) the following :
    ---------------------------------------------
    function Foo(byval a as integer)
    :
    :
    end function
    ---------------------------------------------
    and you're pretty sure about the function signature, you can simply use
    the following Regex :

    (?<result>^func tion Foo\(byval a as integer\).*?end function)
    Note: Set the following RegexOptions : SingleLine and MultiLine

    This will match the required text.

    Explanation: While you're using \w+ to match all the text between the
    function declaration, it will only match word like characters (letters
    and digits). But you must keep in mind, that there is a lot of
    whitespace between the text too and that must be matched as well. So we
    use .*? with the SingleLine setting to enable all whitespace to be
    matched.

    Hope this helps,
    Regards,

    Cerebrus.

    Comment

    • mike

      #3
      Re: need help with regular expression

      Thank you so much.
      It works great. That RegexOptions was a real key factor.

      Comment

      • Cerebrus

        #4
        Re: need help with regular expression

        You're most welcome ! ;-)

        Happy Coding...

        Regards,

        Cerebrus.

        Comment

        Working...