Regular Expression Pattern Matching

Regular Expression Pattern Matching
Regular Expressions let you do pattern matching in VBScript and ASP. In essence, you can validate that any input string matches up to your required letter/number settings.

To start with, you can look for exact matches to characters. So if you look for

ABC

it will match those exact letters, in that exact sequence.

What if you need to match against a range of characters? This is where brackets come in.

If you wanted to accept values of ID1 through ID9, you could set your pattern to be

ID[1-9]

That would match with ID1, ID2, ID3, ID4, ID5, ID6, ID7, ID8, and ID9.

There are also wildcards. If you needed a value to start with SUBJ but have any characters after that point, you could do

SUBJ*

You can also use {#} to say you want a certain number of something. So you can do

[1-9]{9}

if you want to see 9 digits in a row.

Using this logic, a pattern for a social security number would be

[0-9]{3}-[0-9]{2}-[0-9]{4}

A dot is a special character. It is a single wildcard that matches any single character. So you could look for

c.t

and it would match with cat, cot, cut, cet, and so on.

There are two special "anchor" characters. These are ^ and $. The ^ stands for the beginning of a string. It ensures the match starts with the first part of the string. On the other end, the $ represents the ending part of the string.

So if you wanted to find anything that began with the text http, with nothing before it, you would look for

^http

Note that the carat has a second, different meaning when used within brackets []. In that case, it is a "NOT" operator. So if you looked for

an[^d]

it would find the word an but not the word and.

There is also the "or" operator in regular expressions. That is the pipe symbol, or |. You could look for

high|low

to accept either high or low.

You can use a question mark to indicate something is optional. Say you wanted to look for anything with the text

index

and you weren't sure if there was going to be a slash after that word or not. You could look for

index/?

that would match either

index

or

index/

The more you play with regular expressions, the more powerful you realize they are!

To learn how to use these patterns in your code, be sure to read Using Regular Expressions in ASP Coding!




RSS
Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Lisa Shea. All rights reserved.
This content was written by Lisa Shea. If you wish to use this content in any manner, you need written permission. Contact Lisa Shea for details.