I. Overview of regular expressions
If you have not used regular expressions before, you may not be familiar with this term or concept. However, they are not as novel as you might think.
Recall how you found the file on your hard disk. Are you sure you will use it? and * characters to help find the file you are looking for. The character matches a single character in the file name, while the * matches one or more characters. One like ' data?. DAT ' mode can be found in the following files: Data1.dat, Data2.dat and so on. If you use the * character instead? Character, the number of files found will be enlarged. ' Data*.dat ' can match all of the following file names: Data.dat, Data1.dat, Data12.dat, and so on, although this method of searching for files is certainly useful but very limited. and * The limited ability of wildcards allows you to have a concept of what regular expressions can do, but regular expressions are more powerful and flexible.
When we write ASP programs, we often judge the validity of a string, such as whether a string is a number, whether it is a valid email address, and so on. If you do not use regular expressions, then the judgment of the program will be very long and error prone, if the use of regular expressions, these judgments is a very easy job. Later we will describe how to determine the validity of digital and email addresses.
In a typical search and replace operation, you must provide the exact text you want to find. This technique may be sufficient for simple search and replace tasks in static text, but because of its lack of flexibility, it is difficult or even impossible to search for dynamic text.
What can be done with regular expressions?
Tests a pattern of a string. For example, you can test an input string to see if there is a phone number pattern or a credit card number pattern in the string. This is known as data validation.
Replaces text. You can use a regular expression in your document to identify specific text, and then you can delete it all, or replace it with another text.
Extracts a substring from a string based on pattern matching. Can be used to find specific text in text or input fields.
For example, if you need to search the entire Web site to remove some outdated material and replace some HTML formatting tags, you can use regular expressions to test each file to see if there are any material or HTML formatting tags that you want to find in the file. With this method, you can narrow the affected file range to those files that contain the material you want to delete or change. You can then use regular expressions to delete obsolete materials, and finally, you can use regular expressions again to find and replace those that need to be replaced. So, what is the syntax of regular expression syntax?
A regular expression is a literal pattern consisting of ordinary characters (such as characters A through Z) and special characters (called metacharacters). The pattern is described in the lookup text
One or more strings to match when the character body is to be matched. A regular expression is used as a template to match a character pattern with the string being searched for.
Here are some examples of regular expressions that you might encounter:
Copy Code code as follows:
/^\[\t]*$/"^\[\t]*$" matches a blank line.
/\d{2}-\d{5}/"\d{2}-\d{5}" verifies that an ID number consists of a 2-digit number, a hyphen, and a 5-digit number.
/< (. *) >.*<\/\1>/"< (. *) >.*<\/\1>" matches an HTML tag.
The application of regular expression in VBScript
VBScript uses the RegExp object, the Matches collection, and the match object to provide regular expression support functionality. Let's look at an example first.
Copy Code code as follows:
<%
Function regexptest (PATRN, STRNG)
Dim regEx, Match, matches ' Set variable.
Set regEx = New RegExp ' establishes a regular expression.
Regex.pattern = Patrn ' Set mode.
Regex.ignorecase = True ' Sets whether character case is case-sensitive.
Regex.global = True ' Sets global availability.
Set matches = Regex.execute (strng) ' performs a search.
For the match in matches ' traversal matching collection.
Retstr = retstr & "Match found at position"
Retstr = retstr & Match.firstindex & ". Match Value is ' "
Retstr = retstr & Match.value & "'." & "<BR>"
Next
Regexptest = Retstr
End Function
Response.Write Regexptest ("[Ij]s.", IS1 Js2 IS3 is4)
%>
In this example, we look for two words in the string that have no is or JS, ignoring the case. The results of the operation are as follows:
Copy Code code as follows:
Match found at position 0. Match Value is ' IS1 '.
Match found at position 4. Match Value is ' Js2 '.
Match found at position 8. Match Value is ' IS3 '.
Match found at position 12. Match Value is ' is4 '.
Let's introduce the three objects and collections below.
1, the RegExp object is the most important object, it has several attributes, including:
The 0Global property, sets or returns a Boolean value that indicates whether the pattern matches all or only the first of the entire search string. If the search applies to the entire string, the value of the Global property is True, otherwise its value is False. The default setting is False.
The 0IgnoreCase property, sets or returns a Boolean value that indicates whether the pattern search is case-sensitive. If the search is case-sensitive, the IgnoreCase property is False; otherwise, true. The default value is False.
The 0Pattern property, sets or returns the regular expression pattern that is searched. Required option. Always a REGEXP object variable.
2, Match Object
The result of a matching search is stored in the match object, providing access to the read-only property that matches the regular expression. The match object can only be created by using the RegExp object's Execute method, which actually returns a collection of Match objects. All of the Match object properties are read-only. When you execute a regular expression, you may produce 0 or more Match objects. Each match object provides access to the string found by the regular expression search, the length of the string, and the location of the matching index.
0FirstIndex property that returns the location of the match in the search string. The FirstIndex property uses an offset from zero, which is relative to the
The starting position of the search string. In other words, the first character in the string is identified as a character 0
The 0Length property, which returns the length of the match found in the string search.
A 0Value property that returns the matching value or text found in a search string.
3, Matches Collection
The collection of regular Expression Match objects. The Matches collection contains several separate Match objects that can only be created using the Execute method of the RegExp object. As with the independent Match object properties, one of the properties of the matches ' collection is read-only. When you execute a regular expression, you may produce 0 or more Match objects. Each match object provides an access entry to the string that matches the regular expression, the length of the string, and an index that identifies the matching location.
Learning about these three objects and collections, how do you apply them to the judgment and substitution of strings? The three methods of the RegExp object solve the problem, they are the Replace method, the test method, and the Execute method.
1. Replace method
Replaces the text found in the regular expression lookup. Let's take a look at an example: The following example illustrates the use of the Replace method.
Copy Code code as follows:
<%
Function replacetest (PATRN, REPLSTR)
Dim regEx, str1 ' Set variable.
STR1 = "The quick brown fox jumped over the lazy dog."
Set regEx = New RegExp ' establishes a regular expression.
Regex.pattern = Patrn ' Set mode.
Regex.ignorecase = True ' Sets whether case sensitive.
Replacetest = Regex.Replace (str1, Replstr) ' for replacement.
End Function
Response.Write Replacetest ("Fox", "Cat") & "<BR>" Replaces ' Fox ' with ' cat '.
Response.Write Replacetest ("(\s+) (\s+) (\s+)", "$3$2$1") ' exchange of words.
%>
2. Test method
Performs a regular expression search on the specified string and returns a Boolean indicating whether the matching pattern is found. The actual mode of the regular expression search is set by regexp the Pattern property of the object. The Regexp.global property has no effect on the test method.
The test method returns true if a matching pattern is found, otherwise it returns false. The following code illustrates the use of the test method.
Copy Code code as follows:
<%
Function regexptest (PATRN, STRNG)
Dim regEx, RetVal ' Set variable.
Set regEx = New RegExp ' establishes a regular expression.
Regex.pattern = Patrn ' Set mode.
Regex.ignorecase = False ' Sets whether case sensitive.
RetVal = regex.test (strng) ' performs a search test.
If RetVal Then
Regexptest = "Find one or more matches. "
Else
Regexptest = "no match found. "
End If
End Function
Response.Write Regexptest ("is.", "IS1 is2 IS3 is4")
%>
3. Execute method
Performs a regular-expression search on the specified string. The design pattern of a regular expression search is set by RegExp object patterns.
The Execute method returns a matches collection that contains each matching match object found in string. If no match is found, Execute returns an empty matches collection.
third, the use of the JavaScript expression
After JavaScript version 1.2, JavaScript also supports regular expressions.
1, replace
Replace replaces the corresponding content with a regular expression lookup in a string. Replace does not change the original string, just regenerates a new string. If you need to perform a global lookup or ignore case, then add G and I at the end of the regular expression.
Cases:
Copy Code code as follows:
<SCRIPT>
re =/apples/gi;
str = "Apples are round, and Apples are juicy.";
Newstr=str.replace (Re, "oranges");
document.write (NEWSTR)
</SCRIPT>
The result is: "Oranges are round, and oranges are juicy."
Cases:
Copy Code code as follows:
<SCRIPT>
str = "Twas the night before Xmas ...";
Newstr=str.replace (/xmas/i, "Christmas");
document.write (NEWSTR)
</SCRIPT>
The result is: "Twas the night Before Christmas ..."
Cases:
Copy Code code as follows:
<SCRIPT>
Re =/(\w+) \s (\w+)/;str = "John Smith";
NEWSTR = str.replace (Re, "$, $");
document.write (NEWSTR)
</SCRIPT>
The result: "Smith, John."
2. Search
Search uses regular expressions to find the appropriate string, just to determine if there is a string that does not match. If the search succeeds, search returns the location of the matching string, or returns 1.
Search (RegExp)
Copy Code code as follows:
<SCRIPT>
function Testinput (Re, str) {
if (Str.search (re)!=-1)
Midstring = "contains";
Else
Midstring = "does not contain";
document.write (str + midstring + re.source);
}
Testinput (/^[1-9]/i, "123")
</SCRIPT>
3, Match
The match method performs a global lookup, and the lookup results are stored in an array.
Example one:
Copy Code code as follows:
<SCRIPT>
str = "For more information, Chapter 3.4.5.1";
Re =/(chapter \d+ (\.\d) *)/I;
Found = Str.match (re);
document.write (found);
</SCRIPT>
Display results: Chapter 3.4.5.1,chapter 3.4.5.1,.1
Case TWO:
Copy Code code as follows:
<SCRIPT>
str = "ABCDDCBA";
NewArray = Str.match (/D/GI);
document.write (NewArray);
</SCRIPT>
Show Results D, D.
Iv. examples
1, judge the correctness of the number
Copy Code code as follows:
<%@ Language=vbscript%>
<script language= "javascript" runat= "Server" >
function IsNumeric (strnumber) {
Return (Strnumber.search/^ (-|\+) \d+ (\.\d+) $/)!=-1);
}
function Isunsignednumeric (strnumber) {
Return (Strnumber.search/^\d+ (\.\d+) $/)!=-1);
}
function Isinteger (Strinteger) {
Return (Strinteger.search/^ (-|\+) \d+$/)!=-1);
}
function Isunsignedinteger (Strinteger) {
Return (Strinteger.search (/^\d+$/)!=-1);
}
</script>
<HTML>
<BODY>
<b> judge the correctness of the numbers </b>
<%
Dim strtemp
strtemp = CStr (Request.Form ("inputstring"))
If strtemp = "" Then strtemp = "0"
%>
<table border= "1" cellpadding= "4" cellspacing= "2" >
<TR>
<TD align= "Right" ><B> original string </B></TD>
<td><%= strtemp%></td>
</TR>
<TR>
<TD align= "Right" ><B> digital </B></TD>
<td><%=isnumeric (strtemp)%></td>
</TR>
<TR>
<TD align= "Right" ><B> non-negative number </B></TD>
<td><%=isunsignednumeric (strtemp)%></td>
</TR>
<TR>
<TD align= "right" ><B> integer </B></TD>
<td><%=isinteger (strtemp)%></td>
</TR>
<TR>
<TD align= "Right" ><B> non-negative integer () </B></TD>
<td><%=isunsignedinteger (strtemp)%></td>
</TR>
</TABLE>
<form action= "<%=request.servervariables (" Script_name ")%>" method= "Post >
Please enter a digital:<br>
<input type= "text" name= "inputstring" size= "M" ></INPUT><BR>
<input type= "Submit" value= "submitted" ></INPUT><BR>
</FORM>
</BODY>
</HTML>
2, to determine the correctness of the email address
Copy Code code as follows:
<%
Function Isemail (STRNG)
Isemail = False
Dim RegEx, Match
Set regEx = New RegExp
Regex.pattern = "^\w+ (-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ (\.| -) [a-za-z0-9]+) *\. [a-za-z0-9]+$]
Regex.ignorecase = True
Set Match = Regex.execute (strng)
If Match.count then isemail= true
End Function
%>
v. Summary
Above we introduce the basic concepts of regular expressions, and how to use regular expressions in VBScript and JavaScript, while at the same time giving you a sense of sensibility through some examples. Regular expressions have a wide range of applications and can solve many practical problems for everyone. This article introduces the content is only a few preliminary knowledge, there are many grammatical rules need everyone to continue to learn, in practice to find problems, solve problems.