Home All Groups Group Topic Archive Search About

need help with regular expression

Author
14 Mar 2006 2:08 AM
mikekimhome
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(sFileContents) 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.IgnoreCase Or
RegexOptions.Compiled)
            oMatch = oRegex.Match(sFileContents)


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

Author
14 Mar 2006 7:27 AM
Cerebrus
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>^function 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.
Author
14 Mar 2006 6:48 PM
mike
Thank you so much.
It works great. That RegexOptions was a real key factor.
Author
14 Mar 2006 7:58 PM
Cerebrus
You're most welcome ! ;-)

Happy Coding...

Regards,

Cerebrus.