Tagged with "asp" http://www.addedbytes.com/feeds/tag-feed/ en Web Development in Brighton - Added Bytes 2006 120 VBScript for Beginners http://www.addedbytes.com/articles/for-beginners/vbscript-for-beginners/ ASP stands for Active Server Pages, and is a script engine that runs on IIS web servers (or on Apache servers using ChiliASP). Both IIS and ASP are developed by Microsoft. ASP pages can be written in any one of several scripting languages, the most common one (and default) being VBScript. ASP is a server-side scripting engine that allows you to add interactivity to web pages, process data, interact with databases and so on. It provides similar functionality to languages like Perl and PHP, and like PHP does not need to run within a cgi-bin.

There are several versions of ASP, the current one being ASP 3.0 (ASP.NET is a part of the .NET platform, and we are talking here about "classic" ASP only). VBScript itself is a scripting language and subset of Visual Basic.

VBScript contains seven built-in objects, and you will usually be working with these when writing ASP pages. The objects themselves are:

  • Application
  • ASPError
  • ObjectContext
  • Request
  • Response
  • Server
  • Session

For this basic introduction, we need only worry about the Response object. The Response object is responsible for sending information back to a user from the server. Any time you write something to a page using VBScript, you will be using the Response object.

ASP pages always end with the extension ".asp", for example "index.asp". Pages that have this extension, on a properly configured server, will be processed by the ASP scripting engine before being returned to the user. Anything within the tags <% and %> is code and will be processed by the engine.

Which brings us neatly to our first piece of code. The first thing you will learn to do with ASP is use it to write a simple string to a web page (the famous "Hello World"). "A string" is a common name for text data.

<html> <body> <% Response.Write("Hello World!") %> </body> </html>

Copy and paste the above to an empty text file (for example in Notepad). Save it as "vbscript101.asp", and upload it to a server that supports ASP. When you load the page in a browser, you should see the text "Hello World!". If you do, congratulations! You've finished your first script. If not, it may be that your server does not support ASP - the above should work on any server with ASP support.

What you have done in the above example is write out a normal HTML page, but you have used the ASP scripting engine to write out the text within the page. A good start, but not the most useful of tools so far. Next, we'll learn how to use basic variables.

Variables in VBScript are easy to use, but can be confusing at times. It is always a good idea to name your variables so that you can see easily what they refer to. For example, a variable containing a first name might be called "strFirstName". The "str" tells you it is a string, or text, piece of data. The "FirstName" section tells you what the variable contains - in this case a first name. For a year of birth, you might call a variable "intYearOfBirth" - the int telling you this variable contains an integer.

To use these in a script is reasonably simple. To start with, you need to declare the variable - to tell the ASP engine to create the variable - and then assign a value to it. We then write it out to the page, like so:

<html> <body> <% dim strHelloWorld strHelloWorld = "Hello World, Again!" Response.Write(strHelloWorld) %> </body> </html>

Note that when you use the variable with the "Response.Write" section, you should not put quotation marks around it. If you do, the script will just write out "strHelloWorld" as text, rather than writing the value you gave it.

The "dim" line is where you declare the variable. The next line is used to assign the value "Hello World, Again!" to the variable. And the third line is used to write it to the page. If you copy and paste the above as before, and upload the new script and open it in a browser, you should now see the text "Hello World, Again!" on the page. If you do, congratulations, you have just finished your second ASP script.

Still, though, not the most impressive piece of interaction on the web. Next though, we're going to write a more complex script. This time, we're going to create a variable, give it a value of the current hour of the day, and display a piece of text based upon whether it is morning or afternoon.

<html> <body> <% dim intHourOfDay intHourOfDay = hour(now()) if intHourOfDay < 12 then Response.Write("Good Morning World!<br><br>The hour of the day is ") & intHourOfDay else Response.Write("Good Afternoon World!<br><br>The hour of the day is ") & intHourOfDay end if %> </body> </html>

We start this time by declaring a variable, intHourOfDay. The "int" is to remind us later on, if needed, that this variable contains a number, and the "HourOfDay" tells us that the number itself will be the hour of the day. Next, we grab the current time using the "now()" function, and the current hour by using the "hour()" function on the result (the hour function gives us the hour of a date). At this stage, intHourOfDay will contain a number representing the hour of the current day.

Next, we check the value. If the value is less than 12, we know the current time is morning, and write out an appropriate greeting, followed by the hour of the day (you use the & symbol to write more than one thing to a page at once). Otherwise (else) it is afternoon. The "end if" section at the end tells the ASP scripting engine that the "if" section is over, and to carry on from here as normal.

Now, to use this, you simply need to upload this script, as before, to your web server, and open it in a web browser. Your server may be on a different time zone to you, but you can see what hour of the day it thinks it is underneath the greeting. What you should now see is a greeting of either "Good Morning World!" or "Good Afternoon World!" followed by a blank line, then the hour of the day.

And voila - your first piece of interactive web programming. Congratulations, you've taken your first steps in ASP!

Thu, 13 May 2004 09:56:46 +0100 http://www.addedbytes.com/articles/for-beginners/vbscript-for-beginners/ Dave Child ,,
Make URLs and Email Addresses Clickable Automatically with VBScript http://www.addedbytes.com/blog/code/automatically-convert-urls/ VBScript Regular Expressions are, as in other languages, a very powerful tool, allowing you to find and manipulate patterns within strings easily and quickly. The syntax for them can often be a headache, but once you are familiar with them, you will find them invaluable.

One potential application for regular expressions in VBScript is to process text entered into a website via a form. Normal text replacement will allow you to filter out swear words and highlight specific phrases, but regular expressions allow you to go further. The below example demonstrates how to use them to make any valid email addresses or URLs into clickable links programmatically.

The function itself is easy to call, like so:

strTextToProcess = create_links(strTextToProcess)

The create_links function makes use of another function, also included below, called "ereg_replace". This is a simple function to make regular expression text replacement easier, and you can find out more about it in my article about VBScript Regular Expressions.

function create_links(strText) strText = " " & strText strText = ereg_replace(strText, "(^|[\n ])([\w]+?://[^ ,""\s<]*)", "$1<a href=""$2"">$2</a>") strText = ereg_replace(strText, "(^|[\n ])((www|ftp)\.[^ ,""\s<]*)", "$1<a href=""http://$2"">$2</a>") strText = ereg_replace(strText, "(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)", "$1<a href=""mailto:$2@$3"">$2@$3</a>") strText = right(strText, len(strText)-1) create_links = strText end function function ereg_replace(strOriginalString, strPattern, strReplacement) ' Function replaces pattern with replacement dim objRegExp : set objRegExp = new RegExp objRegExp.Pattern = strPattern objRegExp.IgnoreCase = True objRegExp.Global = True ereg_replace = objRegExp.replace(strOriginalString, strReplacement) set objRegExp = nothing end function

Finally, here is a demonstration of the above code in action:

strTextToProcess = "This simple pair of functions, from http://www.addedbytes.com, will take any text and convert valid URLs and email addresses into clickable links. Problems, feedback and suggestions should be sent to dave@addedbytes.com or posted in the comments section, which you can reach through the link below." strTextToProcess = create_links(strTextToProcess) response.write strTextToProcess

The three lines above will output:

This simple pair of functions, from http://www.addedbytes.com, will take any text and convert valid URLs and email addresses into clickable links. Problems, feedback and suggestions should be sent to dave@addedbytes.com or posted in the comments section, which you can reach through the link below.

Tue, 11 May 2004 13:12:17 +0100 http://www.addedbytes.com/blog/code/automatically-convert-urls/ Dave Child
VBScript Pagination http://www.addedbytes.com/blog/code/vbscript-pagination/ One of the first problems many web developers faces is that of pagination. A database query can sometimes results in hundreds, maybe thousands, of results, and they must all be displayed. Without pagination, those results create a huge, unusable mess for any user.

The problem with any automated pagination script is the preservation of variables. There is no point displaying 10 search results on each page of a result set if a site cannot remember what you searched for from one page to the next. This can one very repetitive part of programming web pages - the preservation of variables.

The following script will work around that problems. There is one downside - you must use querystring variables, rather than form variables (set a form to "GET" rather than "POST"), as otherwise the script will not retain the variables from one page to the next.

Other than that, it is very very simple to use. Simply include it on (for example) a search results page, and call it as normal (replacing current_page with the number of the current page, and total_pages with the total number of pages to display, or the variables holding those pieces of information), and the rest will be done for you.

If you wish to use something other than "current_page" as the variable name for the page number in the querystring, you will also need to change that in the script. The easiest way would be to do a simple find and replace on "current_page", though please do back your work up before doing any 'find and replace' work.

call do_pagination(current_page, total_pages)

The following code is based upon the PHP pagination code used in [url=http://www.phpbb.com]phpBB[/url], which is probably why the results may look familiar.

function do_pagination(current_page, total_pages) current_page = cint(current_page) dim url dim strPages : strPages = "" dim intMaxPages dim intMinPages dim intPaginI ' We start be building the URL to add the current_page variable to ... by removing the old current_page data dim objRegExp : set objRegExp = new RegExp objRegExp.Pattern = "(&|\?)?current_page=[^&]*(&|$)" objRegExp.IgnoreCase = true objRegExp.Global = true url = objRegExp.replace(request.ServerVariables("SCRIPT_NAME") & "?" & request.ServerVariables("QUERY_STRING"), "$1") set objRegExp = nothing if (right(url, 1) = "&") then url = left(url, len(url)-1) end if if (right(url, 1) = "?") then url = left(url, len(url)-1) end if ' Right, now we've got a clean url. Add a character to precede the new current_page value, and off we go! if (instr(url, "?") > 0) then url = url & "&" else url = url & "?" end if if (total_pages > 10) then if (total_pages > 3) then intMaxPages = 3 else intMaxPages = total_pages end if for intPaginI = 1 to intMaxPages if (intPaginI = current_page) then strPages = strPages & "<strong>" & intPaginI & "</strong>" else strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>" end if if (intPaginI < intMaxPages) then strPages = strPages & ", " end if next if (total_pages > 3) then if ((current_page > 1) and (current_page < total_pages)) then if (current_page > 5) then strPages = strPages & " ... " else strPages = strPages & ", " end if if (current_page > 4) then intMinPages = current_page else intMinPages = 5 end if if (current_page < total_pages - 4) then intMaxPages = current_page else intMaxPages = total_pages - 4 end if for intPaginI = intMinPages - 1 to intMaxPages + 1 if (intPaginI = current_page) then strPages = strPages & "<strong>" & intPaginI & "</strong>" else strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>" end if if (intPaginI < intMaxPages + 1) then strPages = strPages & ", " end if next if (current_page < total_pages - 4) then strPages = strPages & " ... " else strPages = strPages & ", " end if else strPages = strPages & " ... " end if for intPaginI = total_pages - 2 to total_pages if (intPaginI = current_page) then strPages = strPages & "<strong>" & intPaginI & "</strong>" else strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>" end if if (intPaginI < total_pages) then strPages = strPages & ", " end if next end if else for intPaginI = 1 to total_pages if (intPaginI = current_page) then strPages = strPages & "<strong>" & intPaginI & "</strong>" else strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>" end if if (intPaginI < total_pages) then strPages = strPages & ", " end if next end if do_pagination = strPages end function

Mon, 15 Mar 2004 17:18:00 +0000 http://www.addedbytes.com/blog/code/vbscript-pagination/ Dave Child ,
VBScript Date Format Functions http://www.addedbytes.com/blog/code/vbscript-date-format-functions/ VBScript's date formatting doesn't offer a huge number of options compared to PHP's date() function. While it's relatively easy to just write small snippets of code every time you need to format a date a specific way, life would be much easier if there was a function you could call on time and again to do the work for you.

Below, you will find three date format functions, all of which make some use of Unix timestamps, a concept most ASP developers will not be familiar with. Unix timestamps are defined as the number of seconds since the epoch, 00:00:00 01/01/1970, and are a very sensible way to store dates and times in a database, in my opinion. They are very easy to work with, especially when selecting data from a database, and once you are used to them, they can make life much much simpler.

NOTE: These functions were updated on the 15th March 2004 to fix a couple of known bugs. In addition, any scripts using these functions may need to be tweaked to take account of your locale. Each locale will use a slightly different date and time format, so please check yours before using these functions, or simply set your locale to UK. To set your locale to UK, you can use the code below:


There is also a [url=http://www.microsoft.com/globaldev/reference/lcid-all.mspx]complete list of valid locales[/url] on the Microsoft website, with the values in the right hand column being the ones you will want.

Finally, the "monthname" function is VBScript is not present in every version, so may need to be defined manually. Please see comments on this article for an example.

The first function, UDate(), will convert a normal date into a Unix timestamp. The second function, unUDate(), simply does the reverse, converting any timestamp into a readable date. The last function takes a date and a format string, and returns a formatted date according to what you put into the formatting string.


function UDate(oldDate)
    UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)
end function

In practice, UDate is very easy to use. For example, if you want to know the current Unix time (the number of seconds since the epoch), you would use something like the following, which would give intCurrent_Unix_Time a value of 1069916571 at the time of writing.

intCurrent_Unix_Time = UDate(Now())


function unUDate(intTimeStamp)
    unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
end function

unUDate is as easy to use as UDate. Simply feed in an integer, and it will return a matching date. It will treat the integer as the number of seconds between the epoch and the desired date, and will return a properly formatted date for normal use in VBScript accordingly.


Now here's where it starts to get tricky. formatDate is also quite easy to use, but only once you get the hang of how it works. As you can see from the below, formatDate requires two values to be passed to it. The first, format, is a string telling the function how you would like the date formatted, and the second, intTimeStamp, can be either a Unix timestamp (preferred) or a normal VBScript date.

The format of the string is what we want to make use of to lay out our dates exactly as we would like, and perhaps this is best shown with an example. I would like a date displayed on my site in the following format: "7:11am, Thursday 27th November, 2003". In normal VBScript that would be a pain to format - I'd probably just end up giving up and using the normal VBLongTime and VBLongDate to display something similar. I would prefer complete control though...

The format string for formatDate can include a whole selection of characters to represent certain date or time entities. There's a table of the ones included in this function just below here. The format string needs to include these entities where it wants them to be replaced by the correct time or date value. To get the above formatted date and time, then, I could use the following:

strDateTime = formatDate("%g:%i%a, %l %j%O %F, %Y", UDate(Now()))

That looks a lot harder than it actually is. To tell the function we are aiming to replace a specific entity in the string with a time or date element, we use a symbol made up of a percent sign (%) and a letter. It is a case sensitive function, so be careful you form your format strings correctly. Without further ado, here's a list of the entities you can include in the format string (anything in the string that is not an entity from the list below will still be in the string when it has been processed).

  • %A - AM or PM
  • %a - am or pm
  • %m - Month with leading zeroes (01 - 12)
  • %n - Month without leading zeroes (1 - 12)
  • %F - Month name (January - December)
  • %M - Three letter month name (Jan - Dec)
  • $d - Day with leading zeroes (01 - 31)
  • %j - Day without leading zeroes (1 - 31)
  • %H - Hour with leading zeroes (12 hour)
  • %h - Hour with leading zeroes (24 hour)
  • %G - Hour without leading zeroes (12 hour)
  • %g - Hour without leading zeroes (24 hour)
  • %i - Minute with leading zeroes (01 to 60)
  • %I - Minute without leading zeroes (1 to 60)
  • %s - Second with leading zeroes (01 to 60)
  • %S - Second without leading zeroes (1 to 60)
  • %L - Number of day of week (1 to 7)
  • %l - Name of day of week (Sunday to Saturday)
  • %D - Three letter name of day of week (Sun to Sat)
  • %O - Ordinal suffix (st, nd rd, th)
  • %U - UNIX Timestamp
  • %Y - Four digit year (2003)
  • %y - Two digit year (03)

You can include any of the above in the format string at any point. I would recommend not using a percentage sign if you can help it (except obviously as part of one of the elements above), and in the same vein, using ordinals anywhere except after a number is slightly foolish.

If you would like to see anything else added to the list, above, please email me and I will see what I can do.

The below is the formatDate function itself. To use, simply copy and paste it into a script or include file and call it as above, with whichever format string you require.

function formatDate(format, intTimeStamp)
    dim unUDate, A

    ' Test to see if intTimeStamp looks valid. If not, they have passed a normal date
    if not (isnumeric(intTimeStamp)) then
        if isdate(intTimeStamp) then
            intTimeStamp = DateDiff("S", "01/01/1970 00:00:00", intTimeStamp)
            response.write "Date Invalid"
            exit function
        end if
    end if
    if (intTimeStamp=0) then 
        unUDate = now()
        unUDate = DateAdd("s", intTimeStamp, "01/01/1970 00:00:00")
    end if

    unUDate = trim(unUDate)

    dim startM : startM = InStr(1, unUDate, "/", vbTextCompare) + 1
    dim startY : startY = InStr(startM, unUDate, "/", vbTextCompare) + 1
    dim startHour : startHour = InStr(startY, unUDate, " ", vbTextCompare) + 1
    dim startMin : startMin = InStr(startHour, unUDate, ":", vbTextCompare) + 1

    dim dateDay : dateDay = mid(unUDate, 1, 2)
    dim dateMonth : dateMonth = mid(unUDate, startM, 2)
    dim dateYear : dateYear = mid(unUDate, startY, 4)
    dim dateHour : dateHour = mid(unUDate, startHour, 2)
    dim dateMinute : dateMinute = mid(unUDate, startMin, 2)
    dim dateSecond : dateSecond = mid(unUDate, InStr(startMin, unUDate, ":", vbTextCompare) + 1, 2)

    format = replace(format, "%Y", right(dateYear, 4))
    format = replace(format, "%y", right(dateYear, 2))
    format = replace(format, "%m", dateMonth)
    format = replace(format, "%n", cint(dateMonth))
    format = replace(format, "%F", monthname(cint(dateMonth)))
    format = replace(format, "%M", left(monthname(cint(dateMonth)), 3))
    format = replace(format, "%d", dateDay)
    format = replace(format, "%j", cint(dateDay))
    format = replace(format, "%h", mid(unUDate, startHour, 2))
    format = replace(format, "%g", cint(mid(unUDate, startHour, 2)))

    if (cint(dateHour) > 12) then
        A = "PM"
        A = "AM"
    end if
    format = replace(format, "%A", A)
    format = replace(format, "%a", lcase(A))

    if (A = "PM") then format = replace(format, "%H", left("0" & dateHour - 12, 2))
    format = replace(format, "%H", dateHour)
    if (A = "PM") then format = replace(format, "%G", left("0" & cint(dateHour) - 12, 2))
    format = replace(format, "%G", cint(dateHour))

    format = replace(format, "%i", dateMinute)
    format = replace(format, "%I", cint(dateMinute))
    format = replace(format, "%s", dateSecond)
    format = replace(format, "%S", cint(dateSecond))
    format = replace(format, "%L", WeekDay(unUDate))
    format = replace(format, "%D", left(WeekDayName(WeekDay(unUDate)), 3))
    format = replace(format, "%l", WeekDayName(WeekDay(unUDate)))
    format = replace(format, "%U", intTimeStamp)
    format = replace(format, "11%O", "11th")
    format = replace(format, "1%O", "1st")
    format = replace(format, "12%O", "12th")
    format = replace(format, "2%O", "2nd")
    format = replace(format, "13%O", "13th")
    format = replace(format, "3%O", "3rd")
    format = replace(format, "%O", "th")

    formatDate = format

end function

Mon, 15 Mar 2004 14:07:00 +0000 http://www.addedbytes.com/blog/code/vbscript-date-format-functions/ Dave Child ,,,,,,,,,,,
VBScript Regular Expressions http://www.addedbytes.com/blog/code/vbscript-regular-expressions/ Regular expressions in VBScript are two words that can bring many to their knees, weeping, but they are not as scary as some would have you believe. With their roots in Perl, regular expressions in VBScript use similar syntax, and the chances are that you may already be familiar with the concepts here if you have played with regular expression matching before.

Below, you will find three sections. The first section, Reference, is a simple reference listing the most-used of the various symbols and characters used in regular expressions. The second section, Functions, has two functions in it that may make life easier for you. The third section, Examples, is where the fun begins - examples of regular expressions in action.


Character Sets and Grouping

  • . - Any single character (except new line character, "\n")
  • [] - Encloses any set of characters
  • ^ - Matches any characters not within following set
  • [A-Z] - Any upper case letter between A and Z
  • [a-z] - Any lower case letter between a and z
  • [0-9] - Any digit from 0 to 9
  • () - Group section. Also can then be back-referenced with $1 to $n, where n is the number of groups
  • | - Or. (ab)|(bc) will match "ab" or "bc"


  • + - One or more
  • * - Zero or more
  • ? - Zero or one
  • {5} - Five
  • {1,3} - One to three
  • {2,} - Two or more


  • ^ - Start of string
  • $ - End of string
  • \b - End of word
  • \n - New line
  • \r - Carriage return


  • \ - Escape character
  • \t - Tab
  • \s - White space
  • \w - Matches word (equivalent of [A-Za-z0-9_])

Please note that the escape character mentioned above is not usable in normal VBScript. Regular expression syntax is based upon Perl regular expression syntax. To escape a character in VBScript, you usually double it. For example, the following will print out 'This is a "quoted" piece of text'.

response.write("This is a ""quoted"" piece of text.")


The first of the functions below, ereg (named after the PHP function to keep me from going quite quite mad), is the one you will probably use most. Simply put, if you feed in a string, pattern, and choose whether or not you would like to ignore the case of letters in either, the function will return TRUE if the string contains the pattern, or FALSE if not.

function ereg(strOriginalString, strPattern, varIgnoreCase) ' Function matches pattern, returns true or false ' varIgnoreCase must be TRUE (match is case insensitive) or FALSE (match is case sensitive) dim objRegExp : set objRegExp = new RegExp with objRegExp .Pattern = strPattern .IgnoreCase = varIgnoreCase .Global = True end with ereg = objRegExp.test(strOriginalString) set objRegExp = nothing end function

Next up we have ereg_replace. Like it's shorter cousin, you need to feed it a string, a pattern and choose your case sensitivity. This time, you must also add a replacement. This function will replace all instances of the pattern with the replacement in the string (if you change ".Global = True" to ".Global = False" then the function will only replace the first instance of the pattern with the replacement).

function ereg_replace(strOriginalString, strPattern, strReplacement, varIgnoreCase) ' Function replaces pattern with replacement ' varIgnoreCase must be TRUE (match is case insensitive) or FALSE (match is case sensitive) dim objRegExp : set objRegExp = new RegExp with objRegExp .Pattern = strPattern .IgnoreCase = varIgnoreCase .Global = True end with ereg_replace = objRegExp.replace(strOriginalString, strReplacement) set objRegExp = nothing end function


Example 1: Checking hexadecimal string

A hexadecimal number can be made up of any digit, and any letter, upper or lower case, between a and f, inclusive. So to check if a string is actually hexadecimal, the following will do quite nicely (strOriginalString is the original string to be tested):

<% if ereg(strOriginalString, "[^a-f0-9\s]", True) = True then response.write "String is not hexadecimal." else response.write "String is hexadecimal." end if %>

The pattern, "[^a-f0-9\s]" matches anything that is not in the set of characters specified (so if there is anything in the string that is not in that set, the function will return True). The characters specified are all letters between a and f inclusive, and we've specified a case insensitive match, so upper case letters will be treated the same way. We are also allowing whitespace (new lines, spaces, carriage returns and tabs), which is what the "\s" represents in regular expressions.

Example string that returns False (and is therefore hexadecimal):


Example 2: Masking the last section of an IP address

An IP address is made up of four sets of numbers seperated by periods. It's common practice, if you are going to display visitor (or any) IP address on your site, to mask the last (fourth) set of numbers. Here's a way to use ereg_replace to do just this:

<% strOriginalString = ereg_replace(strOriginalString, "([^0-9])([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.[0-9]{1,3}([^0-9])", "$1$2.$3.$4.***$5", True) %>

This is a little more tricky, as you'd hopefully expect from a second example. It looks harder than it is though, so one step at a time. There are actually only a few entities in the pattern - they are just repeated. The most important is this: "([0-9]{1,3})". It matches a section of an IP adress, and is enclosed in brackets so that this section can be used in the replacement of the pattern as well (otherwise we would not be able to keep the first three parts of the IP address to display). You can see these sections in use, referenced with "$2", "$3" and "$4" in the replacement. The pattern within the brackets simply says "between one and three digits between 0 and 9".

The second repeated section is "\.". We use a backslash before the period to indicate that this period (the character following the backslash) is to be treated as a normal period. We call this an escaped character, and this is a fairly common practice. The period, unescaped (without the backslash), is used as a symbol representing "any character except the new line character".

Example input text:

My IP address is 123.456.78.9 but 4444.1.1.1 is just a bunch of random numbers, and so is 12.34.56, and is another valid IP.

Example output text:

My IP address is 123.456.78.*** but 4444.1.1.1 is just a bunch of random numbers, and so is 12.34.56, and 1.1.1.*** is another valid IP.

Example 3: Making the second word of every sentence in a string bold, as long as the word before only contains upper case letters and the second word does not contain an even digit

Getting more interesting now, this example is not in the least bit useful in practice, but should prove to be a useful demonstration of the power of regular expressions. It sounds tough - but with regular expressions, it's a walk in the park.

<% strOriginalString = ereg_replace(". " & strOriginalString, "(\.|!|\?)\s([A-Z]+)\s([^02468\s]+)\s", "$1 $2 <strong>$3</strong> ", False) strOriginalString = mid(strOriginalString, 2) %>

We start by adding an artificial period and space to the beginning of the string, just to make sure we catch the first sentence, and add a line to strip our extra characters out afterwards. We only want those sentences split with punctuation and a space, or we'll end up with bold decimals and it will be very messy indeed. So, we check for puncuation, followed by a space, followed by a word made entirely of capitals, followed by another space, followed by a second word that doesn't contain even numbers, or whitespace, followed by a space. If we find that, we replace it with the same items we picked up in brackets, only with a <strong></strong> tag pair around the second word.

Example input text:

THE quick brown fox jumped over the lazy dog? Many red balloons blew up! EVEN num2ber sentence. ODD num3ber sentence.

Example output text:

THE quick brown fox jumped over the lazy dog? Many red balloons blew up! EVEN num2ber sentence. ODD num3ber sentence.

Fri, 07 Nov 2003 09:29:40 +0000 http://www.addedbytes.com/blog/code/vbscript-regular-expressions/ Dave Child ,,,,,,,,,,,