Matching Regular Expressions (Regex) in ASP.NET

There may come a time when you want to match a Regular Expression against a string and you don’t necessarily want or need to use one of the built in ASP.Net Regular Expression Validators. For instance, using a validator, if the match doesn’t occur, you are not allowed to submit your form data. But, let’s say, you want to validate the data, but you don’t really mind if the data is a match or not and you merely want to send the user a message that the data didn’t match the correct format.

Using theĀ System.Text.RegularExpressions Namespace (don’t forget to import it!), you can accomplish this in code. Note the following function:

Function RegExMatch(sItem as String, sRegEx as String) as Boolean Dim r As Regex = New Regex(sRegEx) Dim m As Match = r.Match(sItem) Return m.Success End Function

Here, we’re taking the first argument in the function (sItem) and matching it against the Regular Expression, which is in the second argument. Since the Function returns a boolean, naturally, the only two possibilites are TRUE or FALSE.

So, to implement this in code, let’s create a scenario where you are entering parts into your online system. For the partnumber itself, you use the format:
####.## – where all characters must be numeric. The Regular Expression for this would be:
^[1-9][0-9][0-9][0-9]\.[0-9][0-9]

So, in your code, you can do something like this:
Continues…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>