Function to Extract a Regular Expression Pattern From a String

The following function returns the part of the passed string that matches the regular expression provided. You can use this function to get the necessary data from fields in a form, etc.

The function takes three parameters: the string to validate, the regular expression, and the grouping pattern that you need. If the pattern is not found, the function returns an empty string, as shown below:

Protected Shared Function GetWithRegEx(ByVal inputStr As String,    ByVal regexStr As String, ByVal groupStr As String) As String   Dim outStr As String   Dim re As New Regex(regexStr)   If re.IsMatch(inputStr) Then      outStr = re.Replace(inputStr, groupStr)   Else      outStr = Nothing   End If           Return outStrEnd Function

Here’s an example of how to use it. The following code searches for 10 numbers in the input string, and if it finds them, it returns only the numbers, so that you can save them in a file or database, etc.P

ublic Shared Function GetPhone(ByVal inputStr As String) As Object   Dim phoneStr As Object   phoneStr = GetWithRegEx(inputStr,       "[D]*(d{3})[D]*(d{3})[D]*(d{4}).*", "$1$2$3")   If phoneStr = Nothing Then      phoneStr = DBNull.Value   End If   Return phoneStrEnd Function
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: