Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: .NET
Expertise: Intermediate
Mar 31, 2009

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 outStr
End 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 phoneStr
End Function
Cindy Rodriguez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap