Common Applications of Regular Expressions, Part 4By Richard Lowe
In Part 3 we looked at parsing data files with regular expressions. In this final part, we'll look at how to use regular expressions to perform powerful string replacements!
The final example we'll look at is the replace functionality of regular expressions in VBScript. ASP often is called to dynamically apply formatting to the text it retrieves from the numerous data sources it has available to it. One handy feature of VBScript's regular expressions allow it to modify the complex patterns it matches. A prime example of this is the highlighting of certain words, such as keywords in a search by adding HTML tags.
To illustrate this, here is an example of highlighting all references to ".NET" in a string. This string could easily come from any source, such as a database or another web site.
In this example, there are several important things to note. The whole regular expression is enclosed in
(). This tells it to capture any pattern it matches for use later. This captured
match is then referenced in the replacement text by
$1. Up to nine such captures can be done per
match, referenced by
Replace method of the regular
expression object is different from the Replace global function in VBScript. It takes only two parameters,
the string to search in and the replacement text.
Also in the example, a bold tag, with other style attributes was added to surround matching text for emphasis on the ".NET" matches. A search and replace like this could easily highlight search terms from a search of your site, or place automatic links to other pages on keywords that appear in any text.
I hope this exploration of some of the uses of regular expressions have given you ideas about how and where to use them in your web applications. Regular expressions are a very powerful way to extend the functionality of VBScript and JScript's string handling. Visual Basic applications, as well, can benefit from regular expressions. Microsoft has made the VBScript and JScript
RegExp objects available to VB (or
any COM-aware language). Just select Microsoft VBScript Regular Expressions under Project --> References
and the RegExp object is available to extend your VB application's string handling, as well.
There is also a bright future for regular expressions in ASP.NET, as they provide the mechanism for one of
the major forms of server control form validation, and are exposed throughout the whole .NET framework in the
Richard Lowe works as a Development Services Consultant for Spherion's
Technology Business Solutions Group...
System.Text.RegularExpressions namespace! (To learn more about ASP.NET, be sure to check out
the ASP.NET Article Index
Richard Lowe works as a Development Services Consultant for Spherion's Technology Business Solutions Group...