Application of regular Expressions _ regular expressions

Source: Internet
Author: User
Tags valid email address
I. Overview of regular expressions
The application of regular expression in VBScript
The application of regular expression in Vavascript
Iv. examples
V. Summary

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). This pattern describes one or more strings to be matched when looking for a text body. 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:
/^\[\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.
<%
Function regexptest (PATRN, STRNG)
dim regEx, Match, matches ' Set variable.
set regEx = New RegExp ' establishes regular expressions.
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 the search.
for each match in matches ' traverses the 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:
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 '.
 below we will introduce these three objects and collections.
The 1, RegExp object is one of the most important objects, and it has several properties, 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 objects
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 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.
<%
Function replacetest (PATRN, REPLSTR)
dim regEx, Str1 ' Set variable.
STR1 = "The quick brown fox jumped over the lazy dog."
set regEx = New Regexp ' establishes regular expressions.
regex.pattern = Patrn ' Set mode.
regex.ignorecase = True ' setting is 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 pairs.
%>
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.
<%
Function regexptest (PATRN, STRNG)
dim regEx, Retval ' Set variable.
set regEx = New Regexp ' establishes regular expressions.
regex.pattern = Patrn ' Set mode.
regex.ignorecase = False ' setting is 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:
<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:
<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:
<SCRIPT>
Re =/(\w+) \s (\w+)/;str = "John Smith";
NEWSTR = str.replace (Re, "$, $");
Document Write (NEWSTR)
</SCRIPT>
The result: "Smith, John."
2. Search
search a regular expression to find the appropriate string, just to determine whether there is a matching string. If the search succeeds, search returns the location of the matching string, or returns 1.
Search (RegExp)
<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:
<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:
<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
<%@ 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>
The correctness of the <b> judgment number </b>
<%
Dim strtemp
strtemp = CStr (Request.Form ("inputstring"))
If strtemp = "" Then strtemp = "0"
%>
<table border= "1" cellpadding= "4" cellspacing= "2" >
<tr>
&LT;TD align= "Right" ><B> original string </B></TD>
<td><%= strtemp%></td>
</tr>
<tr>
&LT;TD align= "Right" ><B> digital </B></TD>
<td><%=isnumeric (strtemp)%></td>
</tr>
<tr>
&LT;TD align= "Right" ><B> non-negative number </B></TD>
<td><%=isunsignednumeric (strtemp)%></td>
</tr>
<tr>
&LT;TD align= "right" ><B> integer </B></TD>
<td><%=isinteger (strtemp)%></td>
</tr>
<tr>
&LT;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 number:<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
<%
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.