Details about js regular RegExp constructor attributes

Source: Internet
Author: User
Tags constructor regular expression

Question

I. What does (RegExp. $ _) and (RegExp ["$ &"]) mean?
2. What do we often see in RegExp. $1?
If you have read the above two questions, you don't know what it means. It doesn't matter. This article mainly describes the attributes of these regular expressions to construct functions. The first question symbol represents the abbreviation of the regular expression constructor attribute. The second is the constructor attribute used to store the capture group.

RegExp constructor attributes

For the attribute definition, I will re-mention it here:

Input (abbreviated as $ _) is the string to be matched the last time.
LastMatch (abbreviated as $ &)
LastParen (abbreviated as $ +) is the most recently matched capture group.
LeftContext (abbreviated as $ ') text before lastMatch in the input string
LastMatch text in the rightContext (abbreviated as $ ') input string
The Boolean value of multiline ($ *) indicates whether all expressions use the multiline mode.
Example

The definition is too painful. Let's take an example.

Var text = "you are in haorooms blog, read the article ";
Var pattern =/(.) aorooms/g;
If (pattern. test (text )){
Console. log (RegExp. $ _); // you are in haorooms blog. Read this article.
Console. log (RegExp ["$ '"]); // you are in
Console. log (RegExp ["$ '"]); // blog, read the article
Console. log (RegExp ["$ &"]); // haorooms
Console. log (RegExp ["$ +"]); // h
Console. log (RegExp ["$ *"]); // false
}
Of course, you can also skip the shorthand. (Some attributes have browser compatibility issues, which are not supported by Opera and some IE ).

You can also see that some of them use "." and some use []. In fact, they play the same role. When using Chinese characters or special symbols, we usually use [].

Store the constructor attributes of the capture group

The syntax of these attributes is (RegExp. $1, RegExp. $2, RegExp. $3, RegExp. $4, RegExp. $5, RegExp. $6, RegExp. $7, RegExp. $8, RegExp. $9), a total of 9. The official explanation is that these can capture the automatic filling of group strings. In fact, to put it simply, you can obtain strings matching in brackets.

Example:

Var text = "you are in haorooms blog, read the article ";
Var pattern =/(.) ao (...) om (.)/g;
If (pattern. test (text )){
Console. log (RegExp. $1); // h
Console. log (RegExp. $2); // ro
Console. log (RegExp. $3); // s
 }


Case 1 test method test

// Test method, test string. true is returned when the mode is met; otherwise, false is returned.
Var re =/he/; // The simplest regular expression that matches the word he.
Var str = "he ";
Console. log (re. test (str); // true
Str = "we ";
Console. log (re. test (str); // false
Str = "HE ";
Console. log (re. test (str); // false, in upper case. You can specify the I flag if both cases are required (I indicates ignoreCase or case-insensitive)
Re =/he/I;
Console. log (re. test (str); // true
Str = "Certainly! He loves her! ";
Console. log (re. test (str); // true, as long as it contains he (HE), it will match. If it is only he or HE and cannot contain other characters, you can use ^ and $
Re =/^ he/I; // escape character (^) indicates the starting position of the character
Console. log (re. test (str); // false, because he is not at the beginning of str
Str = "He is a good boy! ";
Console. log (re. test (str); // true, He is the starting position of the character, and $
Re =/^ he $/I; // $ indicates the character ending position
Console. log (re. test (str); // false
Str = "He ";
Console. log (re. test (str); // true
// Of course, we cannot find how powerful the regular expression is, because we can use = or indexOf in the above example.
Re =/\ s/; // \ s matches any blank characters, including spaces, tabs, and page breaks.
Str = "user Name"; // The user Name contains spaces
Console. log (re. test (str); // true
Str = "user Name"; // The user Name contains tabs.
Console. log (re. test (str); // true
Re =/^ [a-z]/I; // [] matches any character in the specified range. English letters are matched here, which are case insensitive.
Str = "variableName"; // the variable name must start with a letter
Console. log (re. test (str); // true
Str = "123abc ";
Console. log (re. test (str); // false

Case 2 exec test

Var haoVersion = "Haorooms 8"; // The Value 8 indicates the system master version.
Var re =/^ [a-z] + \ s + \ d + $/I; // + indicates that the character must appear at least once, and \ s indicates a blank character, \ d indicates a number
Console. log (re. test (haoVersion); // true, but we want to know the main version number.
// The exec method returns an array. The first element of the array is the complete matching content.
Re =/^ [a-z] + \ s + \ d + $/I;
Arr = re.exe c (haoVersion );
Console. log (arr [0]); // outputs the complete haoVersion, because the entire string exactly matches the re
// I only need to retrieve numbers
Re =/\ d + /;
Var arr = re.exe c (haoVersion );
Console. log (arr [0]); // 8

// The array 1st to nelement returned by exec contains any child match in the match.
Re =/^ [a-z] + \ s + (\ d +) $/I; // use () to create a submatch
Arr implements re.exe c (haoVersion );
Console. log (arr [0]); // The full match of the entire haoVersion, that is, the regular expression
Console. log (arr [1]); // 8, the first child matches, and the main version can also be retrieved in this way.
Console. log (arr. length); // 2
HaoVersion = "Haorooms 8.10"; // Obtain the primary and secondary versions.
Re =/^ [a-z] + \ s + (\ d + )\. (\ d +) $/I ;//. is one of the metacharacters of a regular expression. To use its literal meaning, it must be escaped.
Arr = re.exe c (haoVersion );
Console. log (arr [0]); // Complete haoVersion
Console. log (arr [1]); // 8
Console. log (arr [2]); // 10

Case 3 some methods of String objects related to regular expressions

1. About replace, I wrote a blog dedicated to it. You can also pass parameters.

2. Other operations

// Replace method, used to replace strings
Var str = "some money ";
Console. log (str. replace ("some", "much"); // much money
// The first parameter of replace can be a regular expression.
Var re =/\ s/; // white space character
Console. log (str. replace (re, "%"); // some % money
// The regular expression is extremely convenient when you do not know how many blank characters are in the string
Str = "some \ tsome \ t \ f ";
Re =/\ s + /;
Console. log (str. replace (re, "#"); // However, this will only replace a bunch of blank characters that appear for the first time.
// Because a regular expression can only be matched once, \ s + will exit after matching the first space.
Re =/\ s +/g; // g, global flag, will make the regular expression match the entire string
Console. log (str. replace (re, "@"); // some @
// The other is similar to the split
Var str = "a-bd-c ";
Var arr = str. split ("-"); // returns ["a", "bd", "c"]
// If str is input by the user, it may input a-bd-c or a bd c or a_bd_c, but not abdc (in this case, it is wrong)
Str = "a_db-c"; // The user adds the separator s in his favorite way
Re =/[^ a-z]/I; // As we mentioned earlier, ^ indicates the start of a character, but in [] it indicates a negative character set
// Match any character that is not within the specified range. All characters except letters are matched here.
Arr = str. split (re); // still returns ["a", "bd", "c"];
// IndexOf is commonly used in string search. The corresponding method for regular search is search.
Str = "My age is 18. Golden age! "; // The Age is not certain. We cannot use indexOf to find its location.
Re =/\ d + /;
Console. log (str. search (re); // return the searched string start subscript 10
// Note: Because the search itself returns immediately after the first occurrence, you do not need to use the g flag in search.
// Although the following code does not make an error, the g mark is redundant.
Re =/\ d +/g;
Console. log (str. search (re); // still 10

Var str = "My name is CJ. Hello everyone! ";
Var re =/[A-Z] // match all uppercase letters
Var arr = str. match (re); // returns an array
Console. log (arr); // The array contains only one M, because global match is not used.
Re =/[A-Z]/g;
Arr = str. match (re );
Console. log (arr); // M, C, J, H
// Extract words from strings
Re =/\ B [a-z] * \ B/gi; // \ B indicates the word boundary
Str = "one two three four ";
Console. log (str. match (re); // one, two, three, four

Case 4: some attributes of the RegExp object instance

Var re =/[a-z]/I;
Console. log (re. source); // output the [a-z] string
// Note that the regular expression, along with the forward slash and sign, is output in console. log (re) directly. This is defined by the re. toString method.

Varre =/[A-Z]/;
// After the exec method is executed, the lastIndex attribute of re is modified,
Var str = "Hello, World !!! ";
Var arr = re.exe c (str );
Console. log (re. lastIndex); // 0, because the global flag is not set
Re =/[A-Z]/g;
Arr = re.exe c (str );
Console. log (re. lastIndex); // 1
Arr = re.exe c (str );
Console. log (re. lastIndex); // 7

Varre =/[A-Z]/;
Var str = "Hello, World !!! ";
Re. Lastindexes = 120;
Var arr = re.exe c (str );
Console. log (re. lastIndex); // 0
Case 5 static attributes of the RegExp object

// Input the final string used for matching (the string passed to the test, exec method)
Varre =/[A-Z]/;
Var str = "Hello, World !!! ";
Var arr = re.exe c (str );
Console. log (RegExp. input); // Hello, World !!!
Re.exe c ("tempstr ");
Console. log (RegExp. input); // it is still Hello, World !!!, Because tempstr does not match
// The last matched character of lastMatch
Re =/[a-z]/g;
Str = "hi ";
Re. test (str );
Console. log (RegExp. lastMatch); // h
Re. test (str );
Console. log (RegExp ["$ &"]); // I, $ & is the short name of lastMatch, but it is required because it is not a valid variable name ..
// The last matched group of lastParen
Re =/[a-z] (\ d +)/gi;
Str = "Class1 Class2 Class3 ";
Re. test (str );
Console. log (RegExp. lastParen); // 1
Re. test (str );
Console. log (RegExp ["$ +"]); // 2
// LeftContext returns the character in the searched string from the starting position of the string to the position before the final match.
// RigthContext returns the character from The Last matching position to the end of the string.
Re =/[A-Z]/g;
Str = "123ABC456 ";
Re. test (str );
Console. log (RegExp. leftContext); // 123
Console. log (RegExp. rightContext); // BC456
Re. test (str );
Console. log (RegExp ["$ '"]); // 123A
Console. log (RegExp ["$ '"]); // C456


Case 6 Precautions for using RegExp to construct a function

Var str = "\? ";
Console. log (str); // only outputs?
Var re = /\? // Will match?
Console. log (re. test (str); // true
Re = new RegExp ("\? "); // Error, because \ is an escape character in the string \? Equivalent? To get \?, Yes \\?
Re = new RegExp ("\\? "); // Correct, will match?
Console. log (re. test (str); // true
Use special characters in regular expressions

// Use hexadecimal notation to represent special characters in ASCII format
Var re =/^ \ x43 \ x4A $/; // match CJ
Console. log (re. test ("CJ"); // true
// You can also use the octal method.
Re =/^ \ 103 \ 112 $/; // match CJ
Console. log (re. test ("CJ"); // true
// You can also use Unicode encoding.
Re =/^ \ u0043 \ u004A $/; // Unicode must begin with u, followed by the four-digit hexadecimal representation of character encoding
Console. log (re. test ("CJ "));

Let's talk about the RegExp constructor attributes first. If you have any questions, please leave a message!

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.