Detailed descriptions of JavaScript RegExp Regular Expression objects

Source: Internet
Author: User

Direct amount syntax

/Pattern/attributes

Syntax for creating a RegExp object:
Copy codeThe Code is as follows:
Var obj = new RegExp (pattern, attributes );

Example 1:
Copy codeThe Code is as follows:
Var pattern =//;
Document.write(pattern.exe c ("asdas "));

Example 2:
Copy codeThe Code is as follows:
Var obj = new RegExp ("");
Document.write(obj.exe c ("asdas "));


The execution results of Case 1 and Case 2 are the same;
Parameters
The pattern parameter is a string that specifies the regular expression mode or other regular expressions.

The attributes parameter is an optional string that contains the attribute "g" (perform a global match to find all matches instead of stopping the first match .) , "I": perform case-insensitive matching. And "m": perform multi-row matching ., It is used to specify global match, case-sensitive match, and multi-row match. Before ECMAScript standardization, the m attribute is not supported. This parameter must be omitted if pattern is a regular expression rather than a string.

Return Value
A new RegExp object with the specified pattern and flag. If the pattern parameter is a regular expression rather than a string, the RegExp () constructor creates a new RegExp object with the same pattern and flag as the specified RegExp.

If RegExp () is called as a function instead of the new operator, it performs the same behavior as when it is called using the new operator. It only returns pattern when pattern is a regular expression, instead of creating a new RegExp object.

Throw
SyntaxError-If pattern is not a valid regular expression, or attributes contains characters other than "g", "I", and "m", this exception is thrown.

TypeError-If pattern is a RegExp object but the attributes parameter is not omitted, this exception is thrown.
RegExp object method:
1. test (): retrieves the value specified in the string. Returns true or false.
Copy codeThe Code is as follows:
Var patt1 = new RegExp ("e ");
Document. write (patt1.test ("The best things in life are free "));

2. exec (): retrieves the value specified in the string. Return the value found and locate it.
Copy codeThe Code is as follows. The returned value is the value found. If no matching is found, null is returned.
3. compile (): You can change the search mode or add or delete the second parameter.
Copy codeThe Code is as follows:
Var patt1 = new RegExp ("e ");
Document. write (patt1.test ("The best things in life are free "));
Patt1.compile ("d ");
Document. write (patt1.test ("The best things in life are free "));

Modifier:

1. g: perform a global match to find all the matches instead of stopping the first match;
When the "g" parameter is used, exec () works as follows:
Locate the first "e" and store its location
If exec () is run again, search from the storage location, find the next "e", and store its location
Copy codeThe Code is as follows:
Var patt1 = new RegExp ("e", "g ");
Do
{
Resultsponpatt1.exe c ("The best things in life are free ");
Document. write (result );
}
While (result! = Null)

RegExp Object Attributes
1: global: whether the RegExp object has a flag.
2: whether the ignoreCase: RegExp object has the flag I.
3: lastIndex: an integer that indicates the start position of the next matching character.
4: multiline: indicates whether the RegExp object has a flag m;
5: source: The source Text of the regular expression.

Copy codeThe Code is as follows:
Var obj = new RegExp (/s /);
Document. write (obj. source );

Methods for String objects that support regular expressions
1: The search () method is used to retrieve the specified substring in the string or the substring that matches the regular expression.
Case Insensitive:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var str = "Visit W3School! "
Document. write (str. search (/w3school/I ))
</Script>

Return Value

The starting position of the first substring in stringObject that matches regexp.

Note:If no matched substring is found,-1 is returned.

Description

The search () method does not perform global match. It ignores the flag. It also ignores the lastIndex attribute of regexp and always searches from the start of the string, which means it always returns the first matching position of stringObject.

 

2: The match () method can be used to retrieve the specified value in a string, or to find matching of one or more regular expressions. This method is similar to indexOf () and lastIndexOf (), but it returns the specified value rather than the position of the string.

Return Value

An array that stores matching results. The content of this array depends on whether regexp has a global flag.

Description

The match () method retrieves the stringObject string to find one or more texts that match regexp. The behavior of this method depends largely on whether regexp has a flag.

If regexp does not mark g, the match () method can only perform one match in stringObject. If no matching text is found, match () returns null. Otherwise, it returns an array containing information related to the matched text it finds. The 0th elements in the array store the matching text, while the remaining elements store the text that matches the regular expression's subexpression. In addition to these regular array elements, the returned array also contains two object attributes. The index attribute declares the position of the starting character of the matching text in the stringObject, And the input attribute declares the reference to the stringObject.

If regexp has a flag, the match () method performs a global search and finds all matching substrings in stringObject. If no matched substring is found, null is returned. If one or more matched substrings are found, an array is returned. However, the content of the array returned by global match is very different from that returned by the former. Its array elements store all matched substrings in stringObject, and there is no index or input attribute.

Note:In global search mode, match () does not provide text information that matches the subexpression, nor declare the position of each matched substring. You can use RegExp.exe c () to retrieve global information ().

Example where the parameter is a string:
Copy codeThe Code is as follows:
Var str = "Hello world! "
Document. write (str. match ("world") + "<br/> ")

Example where the parameter is a regular expression:
Copy codeThe Code is as follows:
Var str = "1 plus 2 equal 3"
Document. write (str. match (/\ d +/g ))

3: The replace () method is used to replace other characters with some characters in the string, or replace a substring that matches the regular expression.

stringObject.replace(regexp/substr,replacement)
 
 
Parameters Description
Regexp/substr

Required. Specifies the substring or RegExp object of the pattern to be replaced.

Note that if the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a RegExp object first.

Replacement Required. A string value. Specifies the function for replacing text or generating replacement text.
Return Value

A new string is usedReplacementIt is obtained after the first match of regexp or all matches.

Description

The replace () method of the string stringObject performs the search and replace operation. It will search for the Child string that matches regexp in stringObject, and then useReplacementTo replace these substrings. If regexp has a global flag, the replace () method replaces all matched substrings. Otherwise, it only replaces the first matched substring.

ReplacementIt can be a string or a function. If it is a string, each match will be replaced by a string. However, the $ character in replacement has a specific meaning. As shown in the following table, it indicates that the string obtained from pattern matching will be used for replacement.

Character Replace text
$1, $2,..., $99 Text that matches the 1st to 99th subexpressions in regexp.
$ & The substring that matches the regexp.
$' Text on the left of the matched substring.
$' Text on the right of the matched substring.
$ Directly count the symbols.

Note:ECMAScript v3 stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself.

String replacement:
Copy codeThe Code is as follows:
Var str = "Visit Microsoft! "
Document. write (str. replace (/Microsoft/, "W3School "))

Global replacement:
Copy codeThe Code is as follows:
Var str = "Welcome to Microsoft! "
Str = str + "We are proud to announce that Microsoft has"
Str = str + "one of the largest Web Developers sites in the world ."
Document. write (str. replace (/Microsoft/g, "W3School "))

Returned result: Welcome to W3School! We are proud to announce that W3Schoolhas one of the largest Web Developers sites in the world. Use a regular expression:
Copy codeThe Code is as follows:
Name = '"a", "B "';
Name. replace (/"([^"] *) "/g," '$1 '");

Function:
Copy codeThe Code is as follows:
Name = 'aaa bbb ccc ';
Uw = name. replace (/\ B \ w + \ B/g, function (word ){
Return word. substring (0, 1). toUpperCase () + word. substring (1 );}
);

4: The split () method is used to split a string into a string array.Syntax
stringObject.split(separator,howmany)

Parameters Description
Separator Required. String or regular expression, which separates stringObject from the specified place.
Howmany Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split, regardless of its length.

Return Value

A string array. The array isSeparatorSplit the string stringObject into substrings at the specified boundary. The strings in the returned array do not includeSeparatorItself.


However, ifSeparatorIf it is a regular expression that contains a subexpression, the returned array contains strings that match these subexpressions (but does not include the text that matches the entire regular expression ).




Tips and comments

Note:If the empty string ("") is usedSeparator, Each character in the stringObject will be split.


Note:The operations executed by String. split () are the opposite to those executed by Array. join.



Modifier
Modifier Description
I Perform case-insensitive matching.
G Perform global match (search for all matches instead of stopping the first match ).
M Perform multi-row matching.



Square brackets

Square brackets are used to find characters in a certain range:


Expression Description
[Abc] Find any character between square brackets.
[^ Abc] Search for any characters that are not in square brackets.
[0-9] Search for any number ranging from 0 to 9.
[A-z] Search for any characters from lowercase to lowercase.
A-Z Search for any characters from uppercase A to uppercase Z.
[A-Z] Search for any characters from a to uppercase Z.
[Adgk] Searches for any character in a given set.
[^ Adgk] Searches for any characters outside the given set.
[Red | blue | green] Find any specified options.



Metacharacters

Metacharacter is a character with special meanings:


Metacharacters Description
. Searches for a single character, except for line breaks and line Terminators.
\ W Search for word characters.
\ W Searches for non-word characters.
\ D Search for numbers.
\ D Searches for non-numeric characters.
\ S Search for blank characters.
\ S Searches for non-blank characters.
\ B Search for matching at the beginning or end of a word.
\ B Searches for matches that are not at the beginning or end of a word.
\ 0 Search for NUL characters.
\ N Find a line break.
\ F Find a break.
\ R Find the carriage return.
\ T Search for tabs.
\ V Search for vertical tabs.
\ Xxx Search for characters specified by octal xxx.
\ Xdd Search for the characters specified by dd in hexadecimal notation.
\ Uxxxx Find the Unicode characters specified by the hexadecimal number xxxx.



Quantifiers
Quantifiers Description
N + Match any string containing at least one n.
N * Match any string containing zero or more n.
N? Match any string containing zero or one n.
N {X} Matches the string that contains X n sequences.
N {X, Y} Matches the string that contains X or Y n.
N {X ,} Matches strings that contain at least X n sequences.
N $ Match any string ending with n.
^ N Match any string starting with n.
? = N Match any string followed by the specified string n.
?! N Match any string that is not followed by the specified string n.
JavaScript RegExp Object Reference Manual

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.