Regular Expression details

Source: Internet
Author: User

The regular expression is a regular expression. It seems that English is better understood than Chinese, that is, checking expression characters
Not compliant !! Regular expressions have a very powerful and complex object Regexp. In javascript1.2
.
Let's take a look at the introduction of regular expressions:
The regular expression object is used to regulate a standard expression (that is, the expression operator does not meet specific requirements, such as whether it is an email
It has the attributes and methods used to check whether the given string meets the rules.
In addition, the attributes of individual regular expression objects created by using the Regexp constructor have been pre-defined.
You can use static attributes of objects at any time.
Core objects:
Available in Javascript 1.2 and NES 3.0 and later versions.
The tosource method is added in Versions later than JavaScript 1.3.
CreateCubeMethod:
Text format or Regexp constructor function.
The text format is as follows:
/Pattern/flags:/mode/flag

The constructor function method is as follows:
New Regexp ("pattern" [, "Flags"]) is new Regexp ("Mode" [, "flag"])

Parameters:
Pattern)
Indicates the text of a regular expression.

Flags)
If this option is specified, flags can be one of the following nominal values:
G: Global match (exact match)
I: Ignore case (case insensitive)
GI: both global match and ignore case (matching all possible values, Case Insensitive)

Note: Do not Mark parameters in text format with quotation marks, while parameters in constructors must be marked with quotation marks. So the following
The expression creates the same regular expression:
/AB + C/I
New Regexp ("AB + C", "I ")

Description:
When using constructor, you must use a normal string to avoid rules (adding the leading character \ To the string.
For example, the following two statements are equivalent:
Re = new Regexp ("\ W + ")
Re =/\ W +/

The following provides a complete list and description of special characters that can be used in regular expressions.

Table 1.3: special characters in Regular Expressions:

Character \
Meaning: For characters, it usually indicates the literal meaning, indicating that the next character is a special character, \ is not interpreted.
For example:/B/matches the character 'B'. By adding a backslash \, that is,/\ B/, before B, the character becomes a special character, indicating
Match the dividing line of a word.
Or:
For a few characters, it is generally described as special. It is pointed out that the subsequent characters are not special, but should be interpreted literally.
For example, * is a special character that matches any character (including 0 characters). For example,/a */indicates that it matches 0 or multiple A characters.
To match the literal *, add a backslash before a. For example,/a \ */matches 'A *'.

Character ^
Meaning: The matched characters must be at the frontend.
For example,/^ A/does not match 'A' in "an A,", but matches 'A' in the top of "an '.

Character $
Meaning: similar to ^, it matches the last character.
For example,/t $/does not match 'T' in "Eater", but matches 'T' in "eat '.

Character *
Meaning: match the first character of * 0 or N times.
For example,/Bo */matches 'boooo' in "A ghost booooed" or 'B' in "A bird warbled", but does not match "a goat g
Any character in runted.

Character +
Meaning: match the character before the plus sign once or N times. It is equivalent to {1 ,}.
For example,/a +/matches all 'A' in "Candy" and "caaaaaaandy '.

Character?
Meaning: match? The first character is 0 or 1 time.
Example:/e? Le? /Match 'El' in "angel" and 'le' in "angle '.

Character.
Meaning: (decimal point) match all single characters except line breaks.
For example,/. N/matches 'any' and 'on' in "Nay, an apple is on the tree", but does not match 'nay '.

Character (X)
Meaning: Match 'X' and record the matched value.
For example,/(FOO)/matches and records 'foo' in "foo bar '. Matching substrings can be returned by the element [1],..., [N] In the result array.
Returned by Regexp object attributes $1,..., $9.

Character X | y
Meaning: Match 'X' or 'y '.
For example,/green | red/matches 'green' in "green apple" and 'red' in "red apple '.

Character {n}
Meaning: Here N is a positive integer. Match the previous n characters.
For example:/a {2}/does not match 'A' in "Candy,", but matches all 'A' in "caandy," and the first two in "caaandy ."
'A '.

Character {n ,}
Meaning: Here N is a positive integer. Match at least n first characters.
For example,/a {2,} does not match 'A' in "Candy", but matches all 'A' in "caandy" and "caaaaaaandy'

Character {n, m}
Meaning: both N and m are positive integers. Match at least n characters at most before M.
For example,/a {}/does not match any character in "cndy", but matches the first two characters in "Candy," 'A', "caandy ,"
'A' and "caaaaaaandy" are the first three 'A'. Note: Even if "caaaaaaandy" contains many 'A', it only matches the first three.
(Aaa ".

Character [xyz]
Meaning: A one-character list that matches any character in the list. You can use a hyphen to indicate a character range.
For example, [ABCD] is the same as [A-C. They match 'B' in "brisket" and 'C' in "ache '.

Character [^ XYZ]
Meaning: A character complement, that is, it matches everything except the listed characters. You can use a hyphen to indicate
Character range.
For example, [^ ABC] is equivalent to [^ A-C]. They first match 'R' in "brisket" and 'H' in "chop '.

Character [\ B]
Meaning: match a space (do not confuse with \ B)

Character \ B
Meaning: match the boundary of a word, such as a space (do not confuse it with [\ B)
For example,/\ bn \ W/matches 'no' in "noonday",/\ WY \ B/matches 'ly 'in "possibly yesterday '.

Character \ B
Meaning: match the non-dividing line of a word
For example,/\ W \ BN/matches 'on' in "noonday",/Y \ B \ W/matches 'Ye 'in "possibly yesterday '.

Character \ CX
Meaning: X is a control character. Matches the control character of a string.
For example,/\ cm/matches the control-m in a string.

Character \ D
Meaning: matching a number is equivalent to [0-9].
For example,/\ D/or/[0-9]/matches '2' in "B2 is the suite number '.

Character \ D
Meaning: match any non-number, which is equivalent to [^ 0-9].
For example,/\ D/or/[^ 0-9]/matches 'B' in "B2 is the suite number '.

Character \ f
Meaning: match a form character

Character \ n
Meaning: match a linefeed.

Character \ r
Meaning: match a carriage return.

Character \ s
Meaning: match a single white space character, including space, tab, form feed, line feed, equivalent to [\ f \ n \ r \ t \ v].
For example,/\ s \ W */matches 'bar' in "foo bar '.

Character \ s
Meaning: match a single character except the white space character, which is equivalent to [^ \ f \ n \ r \ t \ v].
For example,/\ s/\ W * matches 'foo' in "foo bar '.

Character \ t
Meaning: match a tab

Character \ v
Meaning: match a top Tab

Character \ W
Meaning: match all numbers, letters, and underscores, equivalent to [A-Za-z0-9 _].
For example,/\ W/matches 'A' in "apple,", "$5.28,", "5", and "3D '.

Character \ W
Meaning: match other characters except numbers, letters, and underscores, equivalent to [^ A-Za-z0-9 _].
For example:/\ W/or/[^ $ A-Za-z0-9 _]/matches '%' in "50% '.

Character \ n
Meaning: Here N is a positive integer. Match the N value of the last substring of a regular expression (left parentheses ).

For example:/Apple (,) \ sorange \ 1/match 'apple, orange, cherry, Peach. ".
There is a more complete example.
Note: If the number in the left parentheses is smaller than the number specified by \ n, \ n removes the octal escape of a row as the description.

Characters \ ooctal and \ xhex
Meaning: here \ ooctal is an escape value of octal, and \ xhex is a hexadecimal escape value, which can be
An ASCII code is embedded in a regular expression.

When the expression is checked, the text symbol provides the method to edit the regular expression. Use text symbols to make regular expressions
The formula is constant. For example, if you use text symbols in a loop to construct a regular expression
Compile multiple times.
Regular Expression object constructor, for example, new Regexp ("AB + C"), provides runtime compilation for regular expressions. When you know
When the expression pattern changes, you should use the constructor, or you do not know the pattern of the regular expression.
When the source is obtained, such as when the user inputs. Once you have defined a regular expression, it can be used anywhere,
It can also be changed. You can use the compilation method to compile a new regular expression for reuse.
A separated pre-defined Regexp object can be used in each window; that is, each separated JavaScript thread runs
To obtain the Regexp object. Because each script cannot be interrupted in a thread, this ensures that different scripts will not be overwritten.
The value of the Regexp object.
Predefined static attributes of a Regexp object: input, multiline, lastmatch, lastparen, leftcontext,
Rightcontext, and from $1 to $9. The input and Multiline attributes can be preset. The values of other static attributes are executing individual regular expressions.
After the exec and test methods of the expression object, and set after the string match and replace methods are executed.

Attribute
Note that several attributes of the Regexp object have both long names and short names (such as Perl ). These names all point to the same value. Perl is
One typeProgramming LanguageWhile JavaScript imitates its regular expression.

Attribute $1,..., $9
Obtain matched substrings, if any.

Attribute $ _
Reference Input

Attribute $ *
See multiline

Attribute $ &
Refer to lastmatch

Attribute $ +
Refer to lastparen

Attribute $'
Refer to leftcontext

Attribute $'
Refer to rightcontext

Attribute Constructor
Specify the object prototype Function

Attribute global
Determines whether to test whether the regular expression cannot match all strings or only conflicts with the first one.

Attribute ignorecase
Determines whether to ignore the case sensitivity when trying to match a string

Attribute Input
When the regular expression is matched, it is the opposite string.

Property lastindex
Determine where the next match starts

Attribute lastmatch
Last matched character

Property lastparen
The last parenthesized when the substring is matched, if any.

Attribute leftcontext
The substring before the last match.

Attribute multiline
Whether to search for strings in multiple rows.

Attribute prototype
Allow attributes to be appended to all objects

Attribute rightcontext
The substring after the last match.

Attribute source
Mode text

 

 

Method
Compile Method
Compile a regular expression object

Exec Method
Run regular expression matching

Test Method
Test Regular Expression matching

Tosource Method
Returns the text description of an object. You can use this value to create a new object. Ignore object. TOS
Ource method.

Tostring Method
Returns a string that describes the specified object, regardless of the object. tostring object.

Valueof Method
Returns the original value of the specified diagonal. The object. valueof method is not considered.

In addition, this object inherits the watch and unwatch methods of the object.

 

Example:
Example 1: The following sample script uses the replace method to convert words in a string. In the replaced text, the script uses the Global Regexp
The value of the $1 and $2 attributes of the object. Note: When passed as the second parameter to the replace method, the $ attribute name of the Regexp object
Name.
<Script language = "javascript1.2">
Re =/(\ W +) \ s (\ W + )/;
STR = "John Smith ";
Newstr = Str. Replace (Re, "$2, $1 ");
Document. Write (newstr)
</SCRIPT>
Result: "Smith, John ".

Example 2: In the following sample script, Regexp. input is set by the change event processing handle. In the getinfo function, the exec Method
Use the value of Regexp. input as its parameter. Note that Regexp has a $ attribute preset.

<Script language = "javascript1.2">
Function getinfo (ABC)
{
Re =/(\ W +) \ s (\ D + )/;
Re.exe C (ABC. value );
Window. Alert (Regexp. $1 + ", your age is" + Regexp. $2 );
}
</SCRIPT>

Enter your surname and age, and press Enter.
<Form> <input type = "text" name = "nameage" onchange = "getinfo (this);"> </form>
</Html>

$1,..., $9 attributes
Match a substring enclosed in parentheses, if any.
Is the Regexp attribute
Static, read-only

Available in Javascript 1.2, NES 3.0 and later versions
Description: Because input is a static attribute, it is not an attribute of an individual regular expression object. You can use Regexp. Input to access this
Attribute.

The number of substrings that can be added with parentheses is unrestricted, but the regular expression object can only keep the last nine strings. If you want to access all
The matching string in parentheses. You can use the returned array.

These attributes can be used to replace the strings (output results) with the Regexp. Replace method ). When this method is used
First, consider the Regexp object. The following is an example. When the regular expression does not contain parentheses, the script is interpreted as $ n literal.
. (Here N is a positive integer ).

For example:
The following script uses the replace method to change the position of words in a string. In the replaced text string, the script uses a regular expression.
The value of the $1 and $2 attributes of the Regexp object. Note: When they pass parameters to the replace method, $ attribute's
The name of the Regexp object.
<Script language = "javascript1.2">
Re =/(\ W +) \ s (\ W + )/;
STR = "John Smith ";
Newstr = Str. Replace (Re, "$2, $1 ");
Document. Write (newstr)
</SCRIPT>
The output result is Smith and John.

Regular Expression details (2)

For the following newly added objects that are not regular expressions, see the corresponding JavaScript Object Attributes $ _ attribute reference input $ * attribute
For details about multiline $ & attributes, refer to lastmatch $ + attributes refer to lastparen $ 'attributes
Refer to the leftcontext $ 'attribute. Refer to the rightcontext compile method to compile a regular expression object during script running.
The Regexp method provides the syntax in Javascript 1.2 and NES 3.0 and later versions:
Regexp. Compile (pattern [, flags]) is the name of a number: Regexp regular expression. It can be a variable name or a text string.
The definition Text of the regular expression pattern. If flags is specified, it can be one of the following: "G": matches all possible strings.
"I": case-insensitive "Gi": matches all possible strings and case-insensitive descriptions:
Use the compile method to compile a regular expression created with the Regexp constructor function. This way
It forces the regular expression to be compiled only once instead of once every time a regular expression is encountered. When you confirm that the regular expression can
When it remains unchanged, you can use the compile method to compile it (after obtaining its matching mode), so that it can be used multiple times in the script.
You can also use the compile method to change the regular expression during running. For example, if the regular expression changes,
You can use the compile method to recompile the object to improve efficiency.
This method changes the values of the source, global, and ignorecasesource attributes of the regular expression. Constructor
Specifies the function used to create an object prototype. Note that the value of this attribute is provided by the function itself, rather than the name. Property of a string containing Regexp.
In JavaScript 1.1, NES 2.0 and later provide the ECMA version ECMA-262 Description: Refer to object. constructor.
The exec method runs the matching search on the specified string. Returns an array of results. Is the Regexp Method
In JavaScript 1.2, NES 3.0 and later versions provide the Syntax: regexp.exe C ([STR]) Regexp ([STR]).
Parameter: Regexp, the name of the regular expression. It can be a variable name or a text definition string.
STR, which matches the string of the regular expression. If omitted, the value of Regexp. input is used.
Description: As in the syntax, execute of the expression can be directly called (using regexp.exe C (STR) or indirectly called (using Regexp (STR )).
If you just run it to find out whether it matches, you can use the string SEARCH method.
If the matching is successful, the exec method returns an array and updates the value of the regular expression object attribute with the pre-defined Regular Expression object and Regexp. If the matching fails, the exec method returns NULL.
See the following example: <script language = "javascript1.2"> // match a B, followed by one or more d, followed by a B
// Ignore case-insensitive myre =/d (B +) (d)/ig; myarray = myre.exe C ("cdbbdbsbz ");
</SCRIPT> The following is the returned value of the script: Object attribute/index Description Example.
Myarray

Myarray content ["dbbd", "BB", "D"]
Index
Match index 1 based on 0
Input
Original string cdbbdbsbz
[0]
Last matched character dbbd
[1],... [N]
A matching string enclosed in parentheses, if any. Do not limit the number of parentheses. [1] = bb
[2] = d
Myre
Lastindex
Index value 5 of the next matching operation
Ignorecase
Specifies whether "I" is used to ignore case sensitivity. True
Global
Indicates whether to use the "G" flag to match all possible strings. True
Source
Define the pattern text string D (B +) (d)
Regexp
Lastmatch $ &
Last matched character dbbd
Leftcontext $ \ q
The latest matching substring C
Rightcontext $'
Bsbz
$1,... $9
Matching substring in parentheses, if any. The number of parentheses is not limited, but Regexp can only retain the last 9 $1 = bb
$2 = d
Lastparen $ +
The last matching substring with parentheses, if any, d

If your regular expression uses the "G" mark, you can use the exec method multiple times to continuously match the same string. When you do this
The New Match starts from the substring determined by the lastindex attribute value of the regular expression. For example, assume that you use the following script:
<Script language = "javascript1.2"> myre =/AB */g; STR = "abbcdefabh"
Myarray = myre.exe C (STR );
Document. writeln ("found" + myarray [0] + ". Next match starts at" + myre. lastindex)
Mysecondarray = myre.exe C (STR );
Document. writeln ("found" + mysecondarray [0] + ". Next match starts at" + myre. lastindex)
</SCRIPT> the script displays the following results: Found abb. Next match starts at 3
Found AB. Next match starts at 9 example:
In the following example, the user enters a name and the script performs the matching operation based on the input. Then, check the array to see if it matches the names of other users.
This script assumes that the name of a registered user has been saved in array A and may be obtained from a database. <HTML>
<Script language = "javascript1.2"> A = ["Zhao", "Qian", "Sun", "Li", "Liang"]
Function Lookup () {firstname =/\ W +/I (); If (! Firstname)
Window. Alert (Regexp. Input + "illegal input"); else {COUNT = 0;
For (I = 0; I enter your surname and press Enter.
<Form> <input type: "text" name = "firstname" onchange = "Lookup (this);"> </form>
</Html> whether the "G" mark is used in the global attribute regular expression. Regexp attribute, read-only
In JavaScript 1.2, NES 3.0 and later versions provide the description that global is an attribute of an object of a unique regular expression.
If the "G" mark is used, the global value is true; otherwise, the global value is false. The "G" Mark specifies a regular expression to test all possible matches.
You cannot directly change the value of this attribute, but you can call the compile method to change it. Ignorecase check whether the regular expression uses the "I" flag
The Regexp attribute is read-only in Javascript 1.2, and the NES 3.0 and later versions provide the description:
Ignorecase is an attribute of an individual regular expression object.
If the "I" flag is used, true is returned; otherwise, false is returned. The "I" mark indicates that case sensitivity is ignored during matching.
You cannot directly change the value of this attribute, but you can call the compile method to change its input and point out that the regular expression needs to test the string. $ _ Is another name of this attribute.
The Regexp attribute is static in Javascript 1.2 and provided by nes 3.0 and later versions.
Description: Because input is static, it is not an attribute of an individual regular expression object. You can also use Regexp. input.
If the exec or test method of the regular expression is not provided with a string and Regexp. Input has a value, its value is used to call this method.
The INPUT attribute can be preset by a script or browser. If the value is preset and the exec or test method is called, the string is not provided.
The input value is used when exec or test is called. Input can be set in the following way in the browser:
When the text form field processing handle is called, the input is set to the string of the text input.
When the textarea form field processing handle is called, the input is set to the input string in the textarea field. Note multili
Ne is also set to true to match multiple lines of text. When the select form field processing handle is called, the input is set to the value of selected text.
When the processing handle of the linked object is called, the input is set to a string between <a href =...> and </a>.
After the event processing is completed, the value of the INPUT attribute is cleared. Lastindex is a readable/writable integer attribute that specifies the start point of the next match.
Regexp attributes are provided in Javascript 1.2 and NES 3.0 and later versions.
Description: lastindex is the attribute of an individual regular expression object. This attribute is set only when the "G" mark of the regular expression is used for full string matching. Follow these rules:
If the length of a large string of lastindexs, regexp.testand regexp.exe C fail, and the lastindex is set to 0.
If lastindex is equal to the length of a string and the regular expression matches an empty string, the regular expression starts from the position of lastindex.
If lastindex is equal to the length of the string and the regular expression does not match an empty string, the regular expression does not match the input and the lastindex is set to 0.
Otherwise, lastindex is set to the next point of the last match. For example, execute the script in the following order: Re =/(HI )? /G match Null String
Re ("hi") Returns ["hi", "Hi"], and sets lastindex to 2.
Re ("hi") Returns [""], an empty array. The element with its subscript 0 is a matching string. In this case, null is returned.
The string is because the lastindex is equal to 2 (and still 2), and the length of "hi" is also 2. Lastmatch matches the string for the last time. $ & means the same.
The Regexp attribute is static and read-only in Javascript 1.2 and NES 3.0 and later versions.
Description: lastmatch is static, so it is not an attribute of a specified regular expression. You can also use Regexp. lastmatch. Lastparen
The last matching string with parentheses, if any. $ + Means the same. Regexp attribute, static, read-only
Available in Javascript 1.2, NES 3.0 and later versions
Description: lastparen is static. It is not a regular expression attribute. You can use Regexp. lastparen to express the same meaning.
The last time leftcontext matches the previous substring, $ 'has the same meaning. Regexp attribute, static, read-only
Available in Javascript 1.2, NES 3.0 and later versions
Description: Because leftcontext is static and is not an attribute of a regular expression, Regexp. leftcontext can be used to express the same meaning.
Multiline indicates whether multiple lines of text are matched. $ * means the same. Regexp attribute, static
Available in Javascript 1.2, NES 3.0 and later versions
Description: Because multiline is static, rather than the attribute of an individual regular expression, Regexp. multiline can be used to express the same meaning.
If multiple lines of text are allowed to be matched, multiline is true. If the search must be stopped in another row, the multiline is false.
The script or browser can set the multiline attribute. When a textarea event processing handle is called, multiline
Set to true. After the event processing handle is processed, the multiline attribute value is cleared. That is to say, if you set multili
If ne is true, multiline is set to false after any event processing handle is executed. Prototype
The prototype of the class. You can use prototype to add class attributes or methods as required. To obtain prototypes Resources
Expected. See the function. Prototype. Property Attribute of Regexp. Starting from JavaScript 1.1 and NES 2.0
ECMA version ECMA-262 rightcontext last matched to the right string, $ 'is the same effect.
Regexp attribute, static, read-only from JavaScript 1.2, NES 3.0 and later versions
Description: Because the rightcontext is static and is not an attribute of an individual regular expression worker, Regexp. rightcontext can be used to achieve the same effect.
Source is a read-only attribute that contains the pattern defined by a regular expression. It does not include forward slashes, G, or I tags. Regexp attribute, read-only
Provided since JavaScript 1.2 and NES 3.0 and later versions
Description: source is the attribute of an individual regular expression object. You cannot directly change its value, but you can change it by calling the compile method. Test
Returns true or false if the regular expression of the specified string matches the search result. Regexp Method
The syntax of Regexp. Test ([STR]) is provided starting with JavaScript 1.2 and NES 3.0 and later versions.
Parameter: Regexp, the name of the regular expression. It can be a variable name or a regular expression that defines a text string.
STR, the string to be matched. If omitted, the value of Regexp. input is used as the parameter.
Description: when you need to know whether a string can match a regular expression, you can use the test method (
Method). To get more information (but the speed will slow down), you can use the exec method (similar to the string. Match Method ). Example: The following example shows whether the test is successful:
Function testinput (Re, STR ){
If (Re. Test (STR) midstring = "contains ";
Else midstring = "does not contain ";
Document. Write (STR + midstring + RE. source);} tosource
Returns the Regexp method of the source code of a string symbolic object. The syntax of tosource () is provided starting from JavaScript 1.3 or later ()
Parameter: Not described: The tosource method returns the following values: For the built-in Regexp object, tosource returns the following symbolic source code unavailable:
Function Boolean () {[native code]}
In Regexp, tosource returns a string indicating the source code. Generally, this method is automatically called by javascript instead Code Explicit call.
For more information, see object. tosource tostring. Regexp Method
Starting with JavaScript 1.1, NES 2.0 provides the ECMA version ECMA-262 Syntax: tostring () parameter: None
Description: The Regexp object does not consider the tostring method of the object. It does not inherit object. tostring.
The tostring method returns a string representing the object. For example, the following example shows the string representing the Regexp object.
Myexp = new Regexp ("A + B + C"); alert (myexp. tostring ())
For more information about displays "/A + B + C/", see: object. tostring valueof returns the original value of a Regexp object.
The Regexp method provides ECMA version from JavaScript 1.1: ECMA-262 Syntax: valueof ()
Parameter: no description: the valueof method of Regexp returns the original value of the Regexp object in string form, which is equal to Regexp. tostring.
This method is usually automatically called by javascript instead of explicitly. Example: myexp = new Regexp ("A + B + C ");
Alert (myexp. valueof () displays "/A + B + C /"

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.