Regular Expression quick start tutorial

Source: Internet
Author: User
Tags valid email address
Regular Expression quick start tutorial

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 a Matches set, which 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 ".

{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}: non-negative integers of m and n. 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]: 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: matches non-word boundary. "Ea * r \ B" matches "ear" in "never early.

\ D: matches 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: matches 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: matches the tab.

\ V: match 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: 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: 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.

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) + [@] {1} (\ w) + [.] {1, 3} (\ w) +"

Next, we will analyze this template carefully. "\ w" indicates that the start character of an email can only be a word character that contains an underscore. This satisfies the third condition; "[@] {1}" indicates that the email address must match only one character "@", meeting condition 1. The same "[.] {1, 3} "indicates that at least one character matches up to three characters in the email". 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, satisfying condition 5; the "(\ w) +" in the template meets Condition 4.

Then, we can directly call the previous function CheckExp ("(\ w) + [@] {1} (\ w) + [.] {1} (\ 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 a template for verifying the ID card number: "([0-9]) {15}"; the template for verifying the URL: "^ http: // {1} (\ w) + [.]) {1, 3} ", etc. 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.

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.

<%
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 +) (\ s +) (\ 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.

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

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:

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

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

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

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

<SCRIPT>
Str = "abcDdcba ";
NewArray = str. match (/d/gi );
Document. write (newArray );
</SCRIPT>

Display result D, d.

1. Determine the correctness of numbers

<% @ 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.

<%
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
%>

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.