JavaScript Tutorial: RegExp constructors

Source: Internet
Author: User
Tags array character classes constructor contains expression implement regular expression string

Article Introduction: ECMAScript supports regular expressions by RegExp types.

ECMAScript supports regular expressions by RegExp types.
var expression =/pattern/flags;
the pattern part can be any simple, complex regular expression that can contain character classes, qualifiers, groupings, forward lookup, and reverse references.
each regular expression can have one or more flags (flags) that indicate the behavior of the regular expression.
Three symbols:
The
g---Represents the global mode, and the pattern applies to all strings, rather than the case of the first occurrence of the discovery
I The---represents a case-insensitive pattern, in which the case of the pattern and string is ignored when a match is determined
m---represents a multiline pattern, that is, when the end of a line of text is reached, it also continues to find occurrences of a pattern match in the next row
An expression of
is a combination of a pattern and the three flags above.
var pattern1 =/at/g//Matching instance of all "at" in the string
var pattern2 =/[ bc]at/i//matches the first ' bat ' or ' cat ', case-insensitive
var pattern3 =/.at/gi//matches all three-character combinations ending with "at", case-insensitive All metacharacters used in the
pattern must be escaped. The metacharacters in a
regular expression include:
([{\ ^ $)? * +.]}
These regular have one or more special uses in the expression, so if you want to match the characters contained in the string, you must escape them
VA R pattern1 =/[bc]at/i; Match the first "bat" or "cat", case-insensitive
var pattern2 =/\[bc\]at/i;//Match the first "[Bc]at", case-insensitive
var pattern3 =/.at/gi;//Match all combinations of 3 characters ending with "at", case-insensitive
var pattern4 =/\.AT/GI//Match all ". At", case-insensitive
using the RegExp constructor, two parameters: string pattern to match, optional flag string
var pattern1 =/[bc]at/i//Match the first "bat" or "cat",
case-insensitive
var pattern2 = new RegExp ("[Bc]at", "I"); Created using constructors
cannot pass regular expression literals to the RegExp constructor
because the pattern of the RegExp constructor is a string, in some cases the character is double escaped.
All metacharacters must be double escaped, and the characters that have been escaped are also so
/\[bc\]at/"\\[bc\\]at"
/\.at/"\\.at"
/name\/age/"Name\\/age"
/\d.\d{1,2}/"\\d.\\dp{1,2}"
/\w\\hello\\123/\\w\\\\hello\\\\ 123
RegExp Instance properties:
Each instance of RegExp has the following instances, through which information about the schema can be obtained;
The
  • Global------Boolean value that indicates whether the G flag
  • ignoreCase------boolean value is set. Indicates whether the I flag
  • lastindex------Integer is set to start the search for the character position of the next occurrence, starting at 0
  • multiline------A Boolean value to indicate whether the M flag
  • is set source-------The string representation of a regular expression, returns
in literal form, which is all contained in the schema declaration
var pattern1 =/\[bc\]at/i
alert (Pattern1.global); False
alert (pattern1.innorecase);//true
Alert (Pattern1.multiline); False
alert (pattern1.lastindex);//0
alert (Pat Tern1.source); "\[bc\]at"
var pattern2 = new RegExp ("\\[bc\\]at", "I")
alert (Pattern2.global); False
Alert (pattern2.innorecase);//true
Alert (pattern2.multiline);//false
Alert (pattern2.lasti NDEX); 0
Alert (pattern2.source);////\[bc\]at
The Source property holds a canonical form of string, that is, the string used in literal form
regexp Real Example method:
The primary method of the
RegExp object is exec (), which is designed specifically for capturing groups
exec () A parameter is the string to which the pattern is to be applied, and the array containing the first occurrence information is returned, or the array returned by null
, if there is no match, is an instance of the array. Contains two additional attributes: Index and input. The
Index represents the position of the match in the string, and input represents the string that applies the regular expression
in the array, the first item is the word that matches the entire pattern String, and other items are strings that match the capturing group in the pattern (if there is no capturing group, contains only one item)
var text = "Mom and dad and baby";
var pattern =/mom (and dad)? /gi;
var matches = pattern.exec (text);
alert (matches.index);//0
alert (matches.input);//"Mom A nd Dad and Baby "
alert (matches[0]);//" Mom and Dad and baby "
alert (matches[1]); "And Dad and Baby"
alert (matches[2]);//"and Baby"
This The example contains two capturing groups, the most internal capturing group matches "and baby", and the capturing group containing him matches "and dad" or "and Dad and Baby"
for the Exec () method, even if The global flag (g) is set in the pattern, and he returns only one match at a time.
calling exec () multiple times on the same string without setting a global flag always returns the information for the first occurrence.
When you set the global flag, each call to EXEC () will continue to find new matches in the string.
var text = "Cat, bat, Sat, fat";
var pattern1 =/.at/;
var matches = pattern1.exec (text);
alert (matches.index);//0
alert (matches[0]);//cat
alert (pattern1.lastindex);//3
matches = pattern1.exec (text);
alert (matches.index);//0
alert (matches[0]);//cat
alert (pattern1.lastindex);//3
var pattern2 =/.at/g;

var matches = pattern2.exec (text);
alert (Matches.index); 0
Alert (matches[0]); Cat
alert (Pattern2.lastindex); 0

matches = pattern2.exec (text);
alert (Matches.index); 5
Alert (matches[0]); Cat
alert (Pattern2.lastindex); 8
The second method of a regular expression is test (), and he accepts a string parameter. Returns true if the pattern matches the parameter, or FALSE.
Test () method The capital is used in the IF statement
var text = "000-00-0000";
var pattern =/\d{3}-\d{2}-\d{4}/;
if (pattern.test (text)) {
alert ("The pattern is matched.");
the toLocaleString () and ToString () methods inherited by the RegExp instance return the literal amount of the regular expression, regardless of how the regular expression was created
RegExp constructor properties:

The RegExp constructor contains some properties. These properties apply to all regular expressions in the scope and vary based on the most recent regular expression operation performed. Another unique thing about these attributes is that they can be accessed in two ways. In other words, these attributes have a long property name, ha a short attribute name (opera is the exception, it does not support short property names). The following table lists the properties of the RegExp constructor.

Long Property name Short attribute name Description
Input $_ The last string to match. Opera does not implement this property
Lastmatch $& The last occurrence of the match. Opera to implement this property
Lastparen $+ Most recently matched capture group
Leftcontext $` Text before lastmatch in the input string
Multiline $* Boolean value that indicates whether all expressions use multiline mode
IE and opera do not implement this property
Rightcontext $ Text after lastmatch in the input string

Use these properties to extract more specific information from the operations performed by exec () or test (). Take a look at the following example:

var text = "This ha been a short summer"; var pattern =/(.) hort/g; if (pattern.test (text)) {alert (regexp.input);//"This has been a short summer" alert (regexp.leftcontext);//"This has bee n A "alert" (Regexp.rightcontext); "Summer" alert (Regexp.lastmatch); "Short" alert (Regexp.lastparen); "S" alert (regexp.multiline); False}

The code above creates a pattern that matches any one character followed by Hort, and puts the first character in a capturing group. The properties of the RegExp constructor return the following values:

    • The input property returns the original string;
    • The Leftcontext property returns the string before the word short, and the Rightcontext property returns the string after short;
    • The Lastmatch property returns the most recent string that matches the entire regular expression, that is, the short
    • The Lastparen property returns the most recent matching capturing group, which is the example s

As mentioned earlier, the long attribute names used by examples can be replaced with the corresponding short attribute names. However, because these short property names are mostly not valid ECMAScript identifiers, they must be accessed through the square brackets method, as follows:

var text = "This has been short summer"; var pattern =/(.) hort/g; if (pattern.test (text)) {alert (regexp.$_);//this has been a short summer alert (regexp["$ '"]);//this has been a alert (Re gexp["s '"]); Summer alert (regexp["$&"]); Short alert (regexp["$+"]); S alert (regexp["$*"]); False}

In addition to the several properties described above, there are up to 9 constructor properties that are used to store capturing groups. The syntax for accessing these properties is Regexp.$1, regexp.$2 ... Regexp.$9, respectively for storage first, second ... The Nineth matching capturing group. These properties are automatically populated when the exec () or test () method is invoked. Then we can use them as follows:

var text = "This has been a short summer"; var pattern =/(..) or (.) /g; if (pattern.test (text)) {alert (regexp.$1);//sh alert (regexp.$2);//t}

This creates a pattern that contains two capturing groups and tests a string with that pattern. Even though the test () method value returns a Boolean value, the properties of the RegExp constructor, and $, are automatically populated with strings that match the corresponding capturing group.



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.