||Regular expressions can be used to replace chunks of text in a string; due to the powerful pattern matching in regular expressions, such search and replace functionality with regular expressions can be much more powerful than using VBScript's |
Replace function. (For information on
Replace be sure to read the FAQ: "How can I replace each occurrence of a particular pattern in a string with another pattern?")
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.
Set regEx = New RegExp
regEx.Global = true
regEx.IgnoreCase = True
' Pattern finds any word (or URL) with
' .NET on the end of it
regEx.Pattern = "(\b[a-zA-Z\._]+?\.NET\b)"
' Input a string to test our replace functionality:
strText = ""
strText = strText & "Microsoft has launched a new Web site," & _
" www.ASP.NET. " & vbCrLf & "This Web site (as you " & _
"can probably guess) contains information " & vbCrLf
strText = strText & "on the next ""version"" of ASP: ASP.NET. The site " & _
"contains links to " & vbCrLf & "download the latest " & _
"ASP.NET bits, contains a FAQ section, links " & vbCrLf
strText = strText & "to ASP community sites, and other great information. " & _
"To learn more " & vbCrLf & "about ASP.NET, check out " & _
"www.ASP.NET and the 4Guys ASP.NET " & vbCrLf
strText = strText & "Article Index! " & vbCrLf
' Call Replace method of the regular expression:
' the $1 means place the matching text here
Response.Write regEx.Replace(strText, _
"<b style='color: #000099; font-size: 18pt'>$1")
View the live demo!
In this example, there are several important things to note. The whole regular expression is enclosed in parenthesis -
(). 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.
-- Taken from Common Applications of Regular Expressions