devxlogo

Function to Extract a Regular Expression Pattern From a String

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
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist