Use of Regular Expression in ASP

Source: Internet
Author: User
Tags valid email address

When creating websites, especially various e-commerce websites, we first ask users to fill in some forms to obtain various information about registered users, because users may enter various types of information, some non-conforming data may cause unnecessary troubles to Our backend ASP processing program, and even cause some security problems to the website. Therefore, before saving the information to the database of the website, we need to verify the validity of the information entered by these users so that subsequent programs can be executed safely and smoothly. Therefore, we usually write an ASP validation program on the backend to analyze whether the user input data is valid.

Someone may ask, isn't JavaScript running on the client better and faster to verify user data? Indeed, this is acceptable in most cases. Why? Because the Javascript you write may not run completely normally on IE and Netscape at the same time, because Microsoft's JScript is not the same as JavaScript, in addition, some browsers are not necessarily compatible with Microsoft and Netscape, so it is very likely that JavaScript on the client will not accurately verify the various types of user input data, while ASP programs are running on the server, it is only related to the environment of your server. No matter what browser the client is, there is no difference for your ASP program, therefore, it is a good choice to use the back-end ASP program for Data Validity verification.

When ASP is used for backend Data Validity verification, some people manually perform data verification in different environments and write a lot of functions. For example, to verify that the URL address entered by a user is valid, you can write a code to analyze the user input information one by one. The amount of information to be analyzed is small, if the analysis conditions are ever-changing, it will be miserable. Not only do you have to write a very long and tedious code, but the running efficiency is extremely low? Is there a good solution? Yes, it is the "Regular Expression" object provided by vbscritp5.0. If your server has ie5.x installed, it will contain vbscript5.0. In fact, "regular expressions" were originally patents under UNIX, especially the most widely used in Perl, because of the powerful functions of "regular expressions, so that Microsoft can port the regular expression object to the Windows system and use

For the "Regular Expression" object, we can easily verify the validity of various types of data.

First, let's take a look at what is VBScript's "Regular Expression" object. Let's first look at a program:

Function checkexp (patrn, strng)

Dim RegEx, match '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.

Matches = RegEx. Test (strng.

Checkexp = matches

End Function

In this program, we can see that we can use "New Regexp" to get a regular expression object, and then assign a value to this object to the regular expression template, that is, to tell the regular expression object, what kind of template Do You Want To match, and then use the method test to check whether the data to be processed exactly matches the template we provide. If not, it indicates that the data to be processed is not legal, and thus the data validity is verified. We can see that a well-designed matching template is used, we can easily verify a batch of similar data information.

Of course, the "Regular Expression" Object in vbscript5.0 has many other methods and attributes, such as method Replace (), with him, we can quickly implement the very fashionable UBB-style forums and BBs on the Internet. This is beyond our scope of discussion and will be discussed later, now let's take a look at the common methods and attributes of Regular Expression objects in data validation:

Common method: Execute Method

Description: searches for a specified string using a regular expression.

Syntax: the syntax of the object. Execute (string) execute method includes the following parts:

Object: required. It is always the name of a Regexp object.

String: required. The text string on which the regular expression is to be executed.

Note: The regular expression search design mode is set through the pattern of the Regexp object. The execute method returns

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

Test Method

Description: performs a regular expression search on the specified string and returns a Boolean value indicating whether a matching pattern is found.

Syntax: object. Test (string)

The syntax of the test method includes the following parts:

Object: required. It is always the name of a Regexp object.

String: required. The text string to be searched by the regular expression.

 

Note: 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.

 

Common attributes: Global attributes

Description: sets or returns a Boolean value, which indicates whether the pattern matches all or only the first character in the entire search string.

Syntax: object. Global [= true | false]

The object parameter is always a Regexp object. 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 true.

Ignorecase attributes

Description: sets or returns a Boolean value to indicate whether the mode search is case sensitive.

Syntax: object. ignorecase [= true | false]

The object parameter is always a Regexp object. If the search is case sensitive, the ignorecase attribute is false; otherwise, the value is true. The default value is true.

Pattern attributes

Description: sets or returns the regular expression pattern to be searched. This is the most important attribute. We mainly set this attribute to implement data verification.

Syntax: object. Pattern [= "searchstring"]

The syntax of the pattern attribute includes the following parts:

Object: required. Always a Regexp object variable.

Searchstring: Optional. The regular string expression to be searched. It may contain various regular expression characters in some tables.

Setting: special characters and sequences are used when writing regular expressions. The following table describes the characters and sequences that can be used and provides examples.

 

Character Description:/: Mark the next character as a special character or literal value. For example, "N" matches the character "N. "/N" matches the linefeed. The sequence "//" matches with "/", and "/(" matches.

^: Match the start position of the input.

$: Matches the end of the input.

*: Match the first character Zero or several times. For example, "zo *" can match "Z" and "Zoo ".

+: Match the previous character once or multiple times. For example, "zo +" can match "Zoo" but does not match "Z ".

? : Match the first character Zero or once. For example, "? Ve? "Matches" ve "in" never ".

.: Match any character other than the line break.

(Pattern) matches the pattern and remembers the matching. The matched substring can be obtained from the matches set used as the result using item [0]... [N. To match the parentheses (and), use "/(" or "/)".

X | Y: matches X or Y. For example, "z | food" can match "Z" or "food ". "(Z | f) Ood" matches "Zoo" or "food ".

: A non-negative integer of N. Match exactly n times. For example, "O" cannot match "O" in "Bob", but can match the first two o in "foooood.

: A non-negative integer of N. Match at least N times. For example, "O" does not match "O" in "Bob", but matches all o in "foooood. "O" is equivalent to "O + ". "O" is equivalent to "O *".

: A non-negative integer between M and N. Match at least N times, at most m times. For example, "O" matches the first three o in "fooooood. "O" is equivalent to "O? ".

[Xyz]: A character set. Matches one of the characters in the brackets. For example, "[ABC]" matches "A" in "plain ".

[^ XYZ]: A negative character set. Match any character that does not exist in this bracket. For example, "[^ ABC]" can match "P" in "plain ".

[A-Z]: a character in a certain range. Matches any character in the specified range. For example, "[A-Z]" matches any lowercase letter between "A" and "z.

[^ M-Z]: A negative character range. Matches a character that is not in the specified range. For example, "[M-Z]" matches any character that is not between "M" and "z.

/B: match the boundary of a word, that is, the position between a word and a space. For example, "ER/B" matches "er" in "never", but does not match "er" in "verb ".

/B: match the non-word boundary. "EA * r/B" matches "ear" in "never early.

/D: match a number character. It is equivalent to [0-9].

/D: matches non-numeric characters. It is equivalent to [^ 0-9].

/F: match with the paging character.

/N: match the linefeed character.

/R: match the carriage return character.

/S: matches with any white characters, including spaces, tabs, and pagination characters. It is equivalent to "[/f/n/R/T/V]".

/S: matches any non-blank characters. It is equivalent to "[^/f/n/R/T/V]".

/T: match the tab.

/V: match the vertical tab.

/W: matches any word characters, including underscores. It is equivalent to "[A-Za-z0-9 _]".

/W: match any non-word character. It is equivalent to "[^ A-Za-z0-9 _]".

/Num: matches num, where num is a positive integer. Reference back to the remembered match. For example, "(.)/1" matches two consecutive identical characters.

/N: Match n, where n is an octal value. The octal value must be 1, 2, or 3 characters long.

For example, "/11" and "/011" Both match a tab. "/0011" is equivalent to "/001" and "1 ". The octal value cannot exceed 256. Otherwise, only the first two characters are considered part of the expression. ASCII code can be used in regular expressions.

/XN: Match n, where n is a hexadecimal value. The hexadecimal value must be exactly two digits long. For example, "/x41" matches "". "/X041" is equivalent to "/x04" and "1 ". ASCII code can be used in regular expressions.

Well, these are the common methods and attributes. The above syntax has already been described in detail, so we don't have to go on to it, next, let's take a look at how to use these methods and attributes to verify the validity of data in specific examples. Let's take an example. For example, we want to verify the email entered by users, so what kind of data is a legal email? I can enter: uestc95@263.net, of course, I will also enter: xxx@yyy.com.cn, but such input is illegal: XXX @ com.cn or @ xxx.com.cn, and so on, therefore, a valid email address must meet at least the following conditions:

1. It must contain one and only one symbol "@".

2. It must contain at least one of the three symbols "."

3. The first character cannot be "@" or "."

4. "@." Or ". @" cannot appear .@

5. The end cannot be the character "@" or "."

Therefore, based on the above principles and the syntax in the above table, we can easily obtain the required template as follows: "(/W) + [@] (/W) + [.] (/W) +"

Next, let's analyze this template carefully. First, "/W" indicates that the start character of an email can only be a word character that contains an underscore. In this way, the third condition is met; "[@]" indicates that the email must match and only match the character "@" once. Condition 1 is met. The same "[.] "indicates that at least one email matches up to three characters". ". The second condition is met. The final" (/W) + "of the template indicates that the ending character can only be a word character including an underscore, meeting condition 5; "(/W) +" in the middle of the template meets Condition 4.

Then, we can directly call the previous function checkexp ("(/W) + [@] (/W) + [.] (/W) + ", string to be verified). If true is returned, the data is valid. Otherwise, the data is incorrect. How can this problem be solved. We can also write out the template for verifying the ID number: "([0-9])"; the template for verifying the URL: "^ http: // (/W) + [.]) "and so on. We can see that these templates provide us with good Reusable Modules and use various templates provided by ourselves or others, we can check the validity of data conveniently and quickly. I believe you will write a very general template.

In this way, we only need to customize different templates to verify the legitimacy of different data. Therefore, the most important attribute of a regular expression object is the "pattern" attribute. As long as you have mastered this attribute, you can use the regular expression object for data verification. </Div> <Div class = postbody> ------------------------------------------- </div> <Div class = postbody> the Regexp object supports simple regular expressions..

Regexp object usage:
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 & "'." & vbcrlf
Next
Regexptest = retstr
End Function

Msgbox (regexptest ("is.", "is1 is2 is3 is4 "))

Regexp Object Attributes

◎ Global attributes

The global attribute is set or a Boolean value is returned, indicating whether the pattern matches all or only the first character in the entire search string.
Syntax
Object. Global [= true | false]
The object parameter is always a Regexp object. 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 true.

Usage of the global attribute (change the value assigned to the global attribute and observe its effect ):
Function regexptest (patrn, strng)
Dim regex' creates a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = true' specifies whether to distinguish uppercase and lowercase letters.
RegEx. Global = true' sets the full nature.
Regexptest = RegEx. Execute (strng.
End Function

Msgbox (regexptest ("is.", "is1 is2 is3 is4 "))

◎ Ignorecase attributes

Set the ignorecase attribute or return a Boolean value to indicate whether the mode search is case sensitive.
Syntax
Object. ignorecase [= true | false]
The object parameter is always a Regexp object. If the search is case sensitive, the ignorecase attribute is false; otherwise, the value is true. The default value is true.

Usage of the ignorecase attribute (change the value assigned to the ignorecase attribute to observe its effect ):
Function regexptest (patrn, strng)
Dim regex' creates a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = true' is used to set Case sensitivity.
Regexptest = RegEx. Execute (strng.
End Function

Msgbox (regexptest ("is.", "is1 is2 is3 is4 "))

◎ Pattern attributes

Set the pattern attribute or return the regular expression pattern to be searched.
Syntax
Object. Pattern [= "searchstring"]
The syntax of the pattern attribute includes the following parts:

Syntax description:
Required. Always a Regexp object variable.
Searchstring is optional. The regular string expression to be searched. It may contain various regular expression characters in some tables.

Set
Special characters and sequences are used when writing regular expressions. The following describes the characters and sequences that can be used and provides examples.
/Mark the next character as a special character or literal value. For example, "N" matches the character "N. "/N" matches the linefeed. The sequence "//" matches with "/", and "/(" matches.
^ Match the start position of the input.
$ Matches the end of the input.
* Matches the first character Zero or several times. For example, "zo *" can match "Z" and "Zoo ".
+ Match the previous character once or multiple times. For example, "zo +" can match "Zoo" but does not match "Z ".
? Match the first character Zero or once. For example, "? Ve? "Matches" ve "in" never ".
. Match any character other than the line break.
(Pattern) matches the pattern and remembers the matching. The matched substring can be obtained from the matches set used as the result using item [0]... [N. To match the parentheses (and), use "/(" or "/)".
X | y matches X or Y. For example, "z | food" can match "Z" or "food ". "(Z | f) Ood" matches "Zoo" or "food ".
{N} n is a non-negative integer. Match exactly n times. For example, "O {2}" cannot match "O" in "Bob", but it can match the first two o in "foooood.
{N,} n is a non-negative integer. Match at least N times. For example, "O {2,}" does not match "O" in "Bob", but matches all o in "foooood. "O {1,}" is equivalent to "O + ". "O {0,}" is equivalent to "O *".
{N, m} m and n are non-negative integers. Match at least N times, at most m times. For example, "O {1, 3}" matches the first three o in "fooooood. "O {0, 1}" is equivalent to "O? ".
[Xyz] A character set. Matches one of the characters in the brackets. For example, "[ABC]" matches "A" in "plain ".
[^ XYZ] A negative character set. Match any character that does not exist in this bracket. For example, "[^ ABC]" can match "P" in "plain ".
[A-Z] indicates characters in a certain range. Matches any character in the specified range. For example, "[A-Z]" matches any lowercase letter between "A" and "z.
[^ M-Z] The negative character range. Matches a character that is not in the specified range. For example, "[M-Z]" matches any character that is not between "M" and "z.
/B matches the boundary of a word, that is, the position between a word and a space. For example, "ER/B" matches "er" in "never", but does not match "er" in "verb ".
/B matches the non-word boundary. "EA * r/B" matches "ear" in "never early.
/D matches a numeric character. It is equivalent to [0-9].
/D matches non-numeric characters. It is equivalent to [^ 0-9].
/F matches the paging character.
/N matches the linefeed character.
/R matches the carriage return character.
/S matches any white characters, including spaces, tabs, and pagination characters. It is equivalent to "[/f/n/R/T/V]".
/S matches any non-blank characters. It is equivalent to "[^/f/n/R/T/V]".
/T matches the tab.
/V matches the vertical tab.
/W matches any word characters, including underscores. It is equivalent to "[A-Za-z0-9 _]".
/W matches any non-word characters. It is equivalent to "[^ A-Za-z0-9 _]".
/Num matches num, where num is a positive integer. Reference back to the remembered match. For example, "(.)/1" matches two consecutive identical characters.
/N matches n, where n is an octal value. The octal value must be 1, 2, or 3 characters long. For example, "/11" and "/011" Both match a tab. "/0011" is equivalent to "/001" and "1 ". The octal value cannot exceed 256. Otherwise, only the first two characters are considered part of the expression. ASCII code can be used in regular expressions.
/XN matches n, where n is a hexadecimal value. The hexadecimal value must be exactly two digits long. For example, "/x41" matches "". "/X041" is equivalent to "/x04" and "1 ". ASCII code can be used in regular expressions.

Usage of the pattern attribute:
Function regexptest (patrn, strng)
Dim regex' creates a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = true' is used to set Case sensitivity.
Regexptest = RegEx. Execute (strng.
End Function

Msgbox (regexptest ("is.", "is1 is2 is3 is4 "))

Regexp object Method

◎ Execute Method

Execute method performs regular expression search on the specified string.
Syntax
Object. Execute (string)
Syntax description
Required. It is always the name of a Regexp object.
String is required. The text string on which the regular expression is to be executed.

Description
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.

Execute method usage:
Function regexptest (patrn, strng)
Dim regex' creates a variable.
Set RegEx = new Regexp 'to create a regular expression.
RegEx. pattern = patrn 'setting mode.
RegEx. ignorecase = false' is case sensitive.
RegEx. Global = true' search all matches.
Regexptest = RegEx. Execute (strng.
End Function

Msgbox (regexptest ("is.", "is1 is2 is3 is4 "))

◎ Replace Method

Replace replaces the text found in regular expression search.
Syntax
Object. Replace (string1, string2)
Syntax description
Required. It is always the name of a Regexp object.
Required by string1. String1 is the string to be replaced by text.
Required by string2. String2 is a replacement text string.

Description
The actual mode of the replaced text is set through the pattern attribute of the Regexp object.
The replace method returns a copy of string1, where the Regexp. Pattern text has been replaced with string2. If no matching text is found, the original copy of string1 is returned.

Usage of the eplace method:
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

Msgbox (replacetest ("Fox", "cat "))
'Replace 'fox' with 'cat '.

In addition, the replace method replaces subexpressions in the mode. Next, replace all the word pairs in the original string with the calls to functions in the previous example:
Msgbox (replacetext ("(/S +)", "$3 $2 $1") 'SWAp pairs of words.

◎ Test Method

The test method performs a regular expression search on the specified string and returns a Boolean value indicating whether the matching mode is found.
Syntax
Object. Test (string)
Syntax description
Required. It is always the name of a Regexp object.
String is required. The text string to be searched by the regular expression.

Description
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.

Usage of the test method:
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

Msgbox (regexptest ("is.", "is1 is2 is3 is4") </div>

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.