Apply Regular Expressions in ASP

Source: Internet
Author: User
Tags valid email address
I. Regular Expression Overview
If you have never used a regular expression, you may not be familiar with this term or concept. However, they are not as novel as you think.

Remember how to find files on the hard disk. Are you sure you want to use? And * characters to help find the file you are looking .? Character matches a single character in the file name, while * matches one or more characters. A file such as 'data ?. The following files can be found in the DAT mode: data1.dat, data2.dat, and so on. If "*" is used instead? Characters to expand the number of files found. 'Data *. dat 'can match all the following file names: Data. dat, data1.dat, data12.dat, etc. Although this method is useful for searching files, it is also very limited .? The limited capabilities of wildcard and * enable you to define what a regular expression can do. However, regular expressions are more powerful and flexible.

Compile ASPProgramThe validity of a string, for example, whether a string is a number or a valid email address. If you do not use a regular expression, the program will be very long and prone to errors. If you use a regular expression, it is easy to make these judgments. The following describes how to determine the validity of numbers and email addresses.

In typical search and replacement operations, you must provide the exact text to be searched. This technology may be sufficient for simple search and replacement tasks in static text, but it is difficult or even impossible to search dynamic text due to its lack of flexibility.

What can I do with a regular expression?

Test a mode of a string. For example, you can test an input string to see if there is a phone number or a credit card number. This is called Data Validity verification.

Replace text. You can use a regular expression in a document to identify a specific text, and then delete it all or replace it with another text.

Extract a substring from the string based on the pattern match. It can be used to search for specific text in text or input fields.

For example, if you need to search the entire web site to delete outdated materials and replace some HTML formatting tags, you can use a regular expression to test each file, check whether there are materials or HTML formatting tags in the file. With this method, you can narrow down the affected files to the files that contain the materials to be deleted or changed. Then, you can use a regular expression to delete outdated materials. Finally, you can use a regular expression to find and replace the tags that need to be replaced.

So what is the syntax of the regular expression syntax?

A regular expression is a text mode consisting of common characters (such as characters A to Z) and special characters (such as metacharacters. This mode describes one or more strings to be matched when searching the text subject. A regular expression is used as a template to match a character pattern with the searched string.

Here are some examples of regular expressions that may be encountered:

The following areCodePart:
/^ \ [\ T] * $/"^ \ [\ t] * $" matches a blank row.
/\ D {2}-\ D {5}/"\ D {2}-\ D {5}" verify that an ID number consists of two digits, A hyphen and a five-digit combination.
/<(. *)>. * <\/\ 1>/"<(. *)>. * <\/\ 1>" matches an HTML Tag.

II. Application of Regular Expressions in VBScript

VBScript supports regular expressions using Regexp objects, matches sets, and match objects. Let's look at an example first.

The following code is used:
<%
Function regexptest (patrn, strng)
Dim RegEx, match, matches 'to create a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = true' specifies whether the characters are case sensitive.
RegEx. Global = true' to set global availability.
Set matches = RegEx. Execute (strng) 'to execute the search.
For each match in matches 'traverses the matching set.
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 find whether the strings contain the word "is" or "JS", regardless of the case. The running result is 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 '.

Next we will introduce these three objects and sets.

1. The Regexp object is the most important object. It has several attributes, including:

○ Global attribute, which sets or returns a Boolean value, indicating whether the pattern matches all or only the first character in the entire search string. If the search is applied to the entire string, the value of the global attribute is true; otherwise, the value is false. The default value is false.

○ Set or return a Boolean value for the ignorecase attribute to indicate whether the mode search is case sensitive. If the search is case sensitive, the ignorecase attribute is false; otherwise, the value is true. The default value is false.

○ Pattern attribute, which sets or returns the regular expression pattern to be searched. Required. Always a Regexp object variable.

2. Match object

Matching search results are stored in the match object, providing access to read-only attributes matching regular expressions.

The match object can only be created through the execute method of the Regexp object. This method actually returns a set of match objects. All the matching object attributes are read-only. When executing a regular expression, zero or multiple match objects may be generated. Each match object provides the access to strings found by regular expressions, the length of strings, and the location of matching indexes.

○ The firstindex attribute returns the matched position in the search string. The firstindex attribute uses the offset calculated from zero. The offset is relative to the start position of the search string. In other words, the first character in the string is identified as 0

○ Length attribute, returns the matching length found in string search.

○ Value attribute, returns the matched value or text found in a search string.

3. Matches set

A set of regular expressions that match objects. The matches set contains several independent match objects, which can only be created using the execute method of the Regexp object. Similar to an independent match object attribute, one attribute of the matches set is read-only. When executing a regular expression, zero or multiple match objects may be generated. Each match object provides the access entry of the string that matches the regular expression, the length of the string, and the index that identifies the matching position.

After learning these three objects and sets, how can they be used to judge and replace strings? The three methods of the Regexp object solve this problem. They are the replace method, test method, and execute method.

1. Replace Method

Replace the text found in the regular expression search. Let's take a look at the example: the example below illustrates the use of the replace method.

The following code is used:
<%
Function replacetest (patrn, replstr)
Dim RegEx, str1' create a variable.
Str1 = "The quick brown fox jumped over the lazy dog ."
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = true' is used to set Case sensitivity.
Replacetest = RegEx. Replace (str1, replstr) 'to replace.
End Function
Response. Write replacetest ("Fox", "cat") & "<br>" 'replaces 'fox' with 'cat '.
Response. Write replacetest ("(\ s +)", "$3 $2 $1") 'exchange word pairs.
%>


2. Test Method

Perform a regular expression search on the specified string and return a Boolean value indicating whether the matching mode is found. The actual pattern of Regular Expression search is set through the pattern attribute of the Regexp object.

The Regexp. Global attribute has no effect on the test method.

If the matching mode is found, the test method returns true; otherwise, false. The following code illustrates the usage of the test method.

The following code is used:
<%
Function regexptest (patrn, strng)
Dim RegEx, retval 'to create a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = false' specifies whether to enable case sensitivity.
Retval = RegEx. Test (strng.
If retval then
Regexptest = "one or more matches are found. "
Else
Regexptest = "no matching found. "
End if
End Function
Response. Write regexptest ("is.", "is1 is2 is3 is4 ")
%>

3. Execute Method

Perform regular expression search on the specified string. The regular expression search design mode is set through the pattern of the Regexp object.

The execute method returns a matches set, which contains each matching match object found in the string. If no match is found, execute returns an empty matches set.

Iii. Use of Regular Expressions in Javascript
Javascript 1.2 and later versions also support regular expressions.

1. Replace

Replace searches for and replaces the corresponding content in a string using a regular expression. Replace does not change the original string, but only generates a new string. To perform global search or ignore case sensitivity, add G and I at the end of the regular expression.

Example:

The following code is used:
<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 ."

Example:

The following code is used:
<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 ..."

Example:

The following code is used:
<SCRIPT>
Re =/(\ W +) \ s (\ W +)/; STR = "John Smith ";
Newstr = Str. Replace (Re, "$2, $1 ");
Document. Write (newstr)
</SCRIPT>

The result is: "Smith, John ".

2. Search

Search searches for the corresponding string through the regular expression, but judges whether there is a matching string. If the search is successful, search returns the position of the matched string; otherwise,-1 is returned.

The following code is used:
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 global search, and the search results are stored in an array.

Example 1:

The following code is used:
<SCRIPT>
STR = "For more information, see Chapter 3.4.5.1 ";
Re =/(Chapter \ D + (\. \ D) *)/I;
Found = Str. Match (re );
Document. Write (found );
</SCRIPT>

Result: Chapter 3.4.5.1, Chapter 3.4.5.1,. 1

Example 2:

The following code is used:
<SCRIPT>
STR = "abcddcba ";
Newarray = Str. Match (/D/Gi );
Document. Write (newarray );
</SCRIPT>

Display result D, D.

Iv. Example

1. Determine the correctness of numbers

The following code is used:
<% @ 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> determine whether a number is correct </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> Number </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">
Enter a number: <br>
<Input type = "text" name = "inputstring" size = "50"> </input> <br>
<Input type = "Submit" value = "Submit"> </input> <br>
</Form>
</Body>
</Html>

2. Check whether the email address is correct.

The following code is used:
<%
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

We have introduced the basic concepts of regular expressions and how to use regular expressions in VBScript and JavaScript. At the same time, we have gained a perceptual knowledge through some examples. Regular Expressions are widely used to solve many practical problems. The content described in this article is only a few preliminary knowledge. There are still many grammar rules that you need to continue to learn and find and solve problems in practice.

Related Article

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.