Sunday, October 15, 2006

Code to parse Html to find value of a Input control using Regular Expression

Here's the code to parse html and find the value in input control. some times .net developers come across a situation where we need to parse the html and find the value in a input control. This code uses regular expression to find the value.

Function
------------
Public Function FindControlValue(ByVal InputHtml As String, ByVal ControlName As String, ByVal ValuePattern As String) As String
Dim reg As String = ""
Dim m1, m2 As Match
Dim options As RegexOptions = RegexOptions.Multiline
Dim matches1, matches2 As MatchCollection
matches1 = Regex.Matches(InputHtml.Replace("""", "'").ToString, reg, options)
For Each m1 In matches1
reg = ValuePattern
matches2 = Regex.Matches(m1.Value, reg, options)
For Each m2 In matches2
Return m2.Value.Replace("'", "").ToString
Next
Next
Return ""
End Function


You can call the function like,

if your input control value is string then
FindControlValue(HtmlResult, "StringControlName", "'\d+'")

if your Input control value is Number then
FindControlValue(htmlResult, "NumericControlName", "'\d+'")

if your Input control value is decimal then
FindControlValue(HtmlResult, "DecimalControlName", "'(\-?\d+\.\d+)'")

Hope this code helpful to some one who surfing my blog.

Happy Coding.

No comments: