need help with regular expression

M

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
 
C

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top