Javascript Regexp object

Source: Internet
Author: User

Javascript provides a Regexp object to perform operations and functions on regular expressions. Each regular expression pattern corresponds to a Regexp instance. You can create an instance of the Regexp object in two ways.

Use Regexp's explicit constructor. Syntax: New Regexp ("pattern" [, "Flags"]).

Use Regexp's implicit constructor in plain text format:/pattern/[flags].

The pattern part is required for the regular expression pattern text to be used. In the first method, the pattern part exists as a javascript string and must be enclosed by double quotation marks or single quotation marks. In the second method, the pattern part is nested between two, quotation marks are not allowed.
The flags part sets the Flag Information of the regular expression, which is optional. If the flags part is set, it exists as a string in the first method; in the second method, it follows the last "/" character in the text form. Flags can be a combination of the following flag characters.

G is the global flag. If this flag is set, the search and replacement operations on a text will take effect for all matching parts of the text. If this flag is not set, only the first matched content is searched and replaced.

I is a case-insensitive flag. If this flag is set, Case sensitivity is ignored during Matching and comparison.

M is a multiline flag. If this flag is not set, the metacharacter "^" only matches the start position of the searched string, the metacharacter "$" only matches the end position of the string to be searched. If this flag is set, "^" can also match the position after "\ n" or "\ r" in the searched string (that is, the beginning of the next row, "$" can also match the position after "\ n" or "\ r" in the searched string (that is, the end of the next row.

<Br/> var mystring = "This is the first regular expression example"; <br/> var myregex = new Regexp ("one "); // create a regular expression <br/> If (myregex. test (mystring) {<br/> alert ("the specified mode is found! "); <Br/>}< br/> else {<br/> alert (" the specified mode is not found. "); <Br/>}< br/>

RunCode

Because "\" in the javascript string is an escape character, when you use an explicit constructor to create a Regexp instance object, replace "\" in the original regular expression. For example, two statements in Code 1.2 are equivalent.

<Br/> var RE1 = new Regexp ("\ D {5}"); <br/> var re2 =/\ D {5 }/; <br/> alert ("RE1 =" + RE1 + "\ nre2 =" + re2); <br/>

Run code

Because the Escape Character in the regular expression mode text is "\", if the regular expression must match the original character "\", the regular expression mode text must be represented by "\". When you create a Regexp Instance Object using an explicit constructor, you need to use "\" to represent the original literal character "\".

 
VaR Re = new Regexp (\\\\).
Static attributes Description
Index It is the starting position of the First Matching content in the current expression mode and starts from 0. The initial value is-1. The index attribute changes every successful match.
Input Returns the current string, which can be abbreviated as $ _. The initial value is an empty string "".
Lastmatch Is the last matching string of the current expression pattern, which can be abbreviated as $ &. Its initial value is an empty string "". The attribute value of lastmatch changes after each successful match.
Lastparen If the enclosed child match exists in expression mode, it is the substring matched by the final child match in the current expression mode, which can be abbreviated as $ +. Its initial value is an empty string "". The value of the lastparen attribute changes each time a successful match is made.
Leftcontext Is all content on the left of the last matching string in the current expression mode. It can be abbreviated as $ '("'" indicates the reverse quotation mark under "ESC" on the keyboard ). The initial value is an empty string "". The attribute value of each successful match changes accordingly.
Rightcontext Is all content on the right of the last matched string in the current expression mode, which can be abbreviated as $ '. The initial value is an empty string "". The attribute value of each successful match changes accordingly.
$1... $9 attributes These attributes are read-only. If the expression mode contains the enclosed child match, $1... The $9 attribute values are the content captured by 1st to 9th child matches. If more than 9 Child matches exist, $1... The $9 attribute corresponds to the last nine Child matches. In an expression mode, you can specify any number of child matches with parentheses, but the Regexp object can only store the last nine Child matches. In the result array returned by some methods of the Regexp instance object, you can obtain the child matching results in All parentheses.

Instance attributes Description
Lastindex It is the next position of the last character in the first match of the current expression mode, which starts from 0 and is often used as the starting position for continued search. The initial value is-1, it indicates that the search starts from the starting position. The value of the lastindex attribute changes each time the matching is successful.
Global It is the starting position of the First Matching content in the current expression mode and starts from 0. The initial value is-1. The index attribute changes every successful match.
Ignorecase Returns the status of the ignorecase flag (I) specified when the Regexp object instance is created. If the I flag is set when the Regexp object instance is created, true is returned for this attribute. Otherwise, false is returned. The default value is false.
Multiline Returns the status of the multiline flag (m) specified when the Regexp object instance is created. If the M flag is set when the Regexp object instance is created, true is returned for this attribute. Otherwise, false is returned. The default value is false.
Source Returns the expression text string specified when the Regexp object instance is created.

instance method description
test the syntax format is test (STR ). This method checks whether a string contains the expression mode specified when the Regexp object instance is created. If yes, true is returned; otherwise, false is returned. If a match is found, the static attributes in the Regexp object are updated to reflect the match.
exec the syntax format is Exec (STR ). This method searches a string using the expression mode specified when the Regexp object instance is created, and returns an array containing the search results.
if a global sign (G) is set for the regular expression, you can perform a continuous search in the string by calling the exec and Test Methods multiple times, each time, the string is searched from the location specified by the value of the lastindex attribute of the Regexp object.
If the global flag is not set, the exec and Test Methods ignore the lastindex attribute value of the Regexp object and start searching from the start position of the string.
If the exec method does not find a match, the return value is null. If a match is found, an array is returned and the static attributes in the Regexp object are updated to reflect the match. Element 0 in the returned array contains the complete matching result, while element 1 ~ N is the result of each sub-match defined in expression mode in sequence.
the array returned by the exec method has three attributes: input, index, and lastindex.
the INPUT attribute is the entire searched string.
the index attribute indicates the position of the string to be searched.
the lastindex attribute indicates the next character position of the last character of the matched substring.
compile the syntax format is compile ("pattern" [, "Flags"]). This method can replace the expression mode used by the Regexp object instance.
the new expression mode is compiled into an internal format, so that the later matching process can be executed faster.
If You Want to reuse an expression in a loop, compiling it will accelerate execution.
however, if any other expression mode is used in the Program , the compiled expression mode is used, this compilation is useless.

<Br/> <! Doctype HTML> <br/> <HTML dir = "LTR" lang = "ZH-CN"> <br/> <pead> <br/> <meta charset = "UTF-8" /> <br/> <title> Regular Expression </title> <br/> <style> <br/> </style> </P> <p> <SCRIPT type = "text/JavaScript" charset = "UTF-8"> <br/> window. onload = function () {</P> <p> var strsrc = "xxa1b01c001yya2b02c002zz"; <br/> var Re =/A (\ D) B (\ D {2}) C (\ D {3})/GI; <br/> var arr, Count = 0; <br/> while (ARR = re.exe C (strsrc ))! = NULL) <br/>{< br/> displayresult (); <br/>}< br/> function displayresult () <br/>{< br/> document. write ("<p> This is a regular expression/<strong style = 'color: red'>" + RE. source + "</strong>/GI pairs <br> \" "<br/> + Regexp. input + "\" for "+ (+ + count) +" Times search result: <br> "); <br/> document. write ("Regexp. the index is "+ Regexp. index + "<br>"); <br/> document. write ("Regexp. lastindex is "+ Regexp. lastindex + "<br>"); <br/> document. write ("Regexp. lastmatch is "+ Regexp. lastmatch + "<br>"); <br/> document. write ("Regexp. lastparen is "+ Regexp. lastparen + "<br>"); <br/> document. write ("Regexp. leftcontext is "+ Regexp. leftcontext + "<br>"); <br/> document. write ("Regexp. the rightcontext is "+ Regexp. rightcontext + "<br>"); <br/> document. write ("Regexp. $1 is "+ Regexp. $1 + "<br>"); <br/> document. write ("Regexp. $2 is "+ Regexp. $2 + "<br>"); <br/> document. write ("Regexp. $3 is "+ Regexp. $3 + "<br>"); <br/> document. write ("Regexp. $4 is "+ Regexp. $4 + "<br>"); <br/> document. write ("Arr. the index is "+ arr. index + "<br>"); <br/> document. write ("Arr. input is "+ arr. input + "<br>"); <br/> document. write ("Arr. lastindex is "+ arr. lastindex + "<br>"); <br/> document. write ("the number of elements in the returned array is" + arr. length + "<br>"); <br/> document. write ("the returned array content is"); <br/> for (VAR I = 0; I <arr. length; I ++) <br/>{< br/> if (I <arr. length-1) <br/> document. write ("\" "+ arr [I] +" \ ","); <br/> else <br/> document. write ("\" "+ arr [I] +" \ ") </P> "); <br/>}</P> <p >}< br/> </SCRIPT> <br/> </pead> <br/> <body> </P> <p> </body> <br/> </ptml> <br/>

Run code

 
VaR Reg =/^ $/I // match the IMG Tag \/\ * ([\ s]) *? \ * \/Match comments/^ [a-zA-Z0-9] [\ W \. \-] + @ [\ W \. \-] + $ /\/(? : [^ \ [/] | \. | \[(? : [^ \] | \.) +]) + \/[Gim] * Regular rvalidurl =/^ ([\ W] + :)? \/\/)? ([\ D \ W] | % [A-fa-f \ D] {2, 2 }) + ([\ D \ W] | % [A-fa-f \ D] {2, 2}) + )? @)? ([\ D \ W] [-\ D \ W] {0,253} [\ D \ W] \.) + [\ W] {2, 4} (: [\ D] + )? (\/([-+ _~. \ D \ W] | % [A-fa-f \ D] {2, 2 })*)*(\? (&? ([-+ _~. \ D \ W] | % [A-fa-f \ D] {2, 2}) = ?) *)? (# ([-+ _~. \ D \ W] | % [A-fa-f \ D] {2, 2 })*)? $ /;
// Idcardvar isok = (val = ""); If (! Isok) {If (/^ \ D {15} $ /). test (VAL) {isok = true;} else if (/^ \ D {17} [0-9xx] $ /). test (VAL) {var Vs = ", X, 9, 8 ". split (","), PS = ", 2 ". split (","), Ss = Val. tolowercase (). split (""), r = 0; For (VAR I = 0; I
// Verify the ID card function idcardcheck (Num) {num = num. touppercase (); // ID card number is 15 or 18 digits, 15 digits are all digits, the first 17 digits are digits, and the last digit is the check digit, it may be a number or character X. If (! (/(^ \ D {15} $) | (^ \ D {17} ([0-9] | x) $ )/. test (Num) {// alert ('the length of the ID card number entered is incorrect, or the number does not comply with the regulations! \ N15 digits must all be numbers, and the last digit of the 18 digits can be numbers or X. '); Return false;} // The checkpoint is generated according to ISO 7064: 1983.mod 11-2. X can be considered as a number 10. // Analyze the birth date and check bit var Len, RE; Len = num. length; If (LEN = 15) {Re = new Regexp (/^ (\ D {6}) (\ D {2}) (\ D {2 }) (\ D {2}) (\ D {3}) $/); var arrsplit = num. match (re ); // check whether the birthday date is correct var dtmbirth = new date ('19' + arrsplit [2] + '/' + arrsplit [3] + '/' + arrsplit [4]); vaR bgoodday; bgoodday = (dtmbirth. getyear () = Number (arrsplit [2]) & (dtmbirth. getmonth () + 1) = Number (arrsplit [3]) & (dtmbirth. getdate () = = Number (arrsplit [4]); If (! Bgoodday) {// alert ('wrong Date of birth in ID card number entered! '); Return false;} else {// convert a 15-digit ID card to an 18-digit ID card. // The value is generated according to ISO 7064: 1983.mod 11-2. X can be considered as a number 10. VaR arrint = new array (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); var arrch = new array ('1', '0', 'x', '9', '8', '7', '6 ', '5', '4', '3', '2'); var ntemp = 0, I; num = num. substr (0, 6) + '19' + num. substr (6, num. length-6); for (I = 0; I

Regular Expression learning notes

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.