JavaScript type System _ Regular expression RegExp type detailed _javascript tips

Source: Internet
Author: User
Tags instance method object object

Front.

The underlying syntax for JavaScript's regular expressions is described earlier. The RegExp class of JavaScript represents regular expressions, and both string and RegExp define methods, and regular expressions allow for powerful pattern matching and text retrieval and substitution. This article describes the RegExp object of the regular expression, and the regular expression involves
To the properties and methods

Object

Regular expressions in JavaScript are represented by RegExp objects, and there are two ways of writing: one is literal writing; the other is the construction function.

Perl notation

Regular expression literal writing, also known as Perl, because the regular expression of JavaScript features from Perl

The regular expression literal is defined as a character that is contained between a pair of slashes (/) and can be set to 3 flags

var expression =/pattern/flags;

The matching pattern for regular expressions supports the following 3 flags:

G: Represents the global mode, where the pattern is applied to all strings, not immediately when the first occurrence is found

I: Indicates a case-insensitive (case-insensitive) pattern that ignores the case of a pattern and a string when a match is determined

M: Multiple-line (multiline) mode, that is, when you reach the end of a line of text, you will continue to find items that match the pattern in the next line

Match string all instances of ' at '
var p =/at/g;
The test () method returns a Boolean value indicating whether a match can be found
console.log (p.test (' ATA '));//true
Console.log (p.test (' ABA '));//false

RegExp Constructors

As with normal built-in objects, REGEXP regular expression objects also support the form of new+regexp () constructors

The RegExp constructor receives two parameters: the string pattern to match (patterns) and the optional flag string (flags), the flag string and the literal number of three flags are identical: ' G ', ' I ', ' m '

The two parameters of the RegExp constructor are strings. and any expression defined using the literal form can use the constructor

Match string all instances of ' at '
var p1 =/at/g;
Ditto
var p2 = new RegExp (' at ', ' G ');

Attention The ECMASCRIPT3 specification stipulates that a regular expression direct amount is converted to a RegExp object when it is executed, and the same object is returned for each operation of the same code that represents the direct amount of the regular expression. The ECMASCRIPT5 specification does the opposite, with a regular expression of the same code representing the direct amount of each

Operation returns the new object. IE6-8 has been implemented in accordance with the ECMASCRIPT5 specification, so there is no compatibility issue

Because regular expression literals do not support variables, if a variable appears in a regular expression, you can only use the RegExp constructor to stitch the variable into the parameters of the RegExp constructor using the string concatenation form

"Tips" gets elements from the class name classname

function Getbyclass (obj,classname) {
  var elements = obj.getelementsbytagname (' * ');
  var result = [];
  var pattern = new RegExp (' (^|\\s) ' + classname + ' (\\s|$) ');
  for (var i = 0; i < elements.length i++) {
    if (pattern.test (Elements[i].classname)) {
      Result.push (elements[i) );
    }
  }
  return result;
}

Instance Properties

Each RegExp instance object contains the following 5 properties

Global:  Boolean value that indicates whether the G flag
IgnoreCase: Boolean value is set to indicate whether the I flag
lastindex:  integer to begin searching the character position of the next occurrence, starting from 0
Multiline:  Boolean value that indicates whether flag m source is set
: A string representation of a regular expression that is returned in literal form rather than in the string pattern in the Passed-in constructor
var pattern = new RegExp (' \\[bc\\]at ', ' I ');
Console.log (Pattern.global);//false
Console.log (pattern.ignorecase);//true  
Console.log ( Pattern.multiline);//false
Console.log (pattern.lastindex);//0
Console.log (Pattern.source);//' \[bc\] At

If the EXEC () or test () function of regexp is used, and the global mode ' G ' is set, the matching of the regular expression starts at the lastindex position and is reset after each mismatch succeeds lastindex. In this way, you can repeat the iteration in the string, looking for each matching result in turn. However, if you need to invoke the same regexp exec () or test () method on different strings, this variable may also bring unexpected matches, so when you replace the string, you explicitly place the regexp lastindex to 0

The Exec () method returns the match in the form of an array
var p =/\w/g;
var s = ' ab ';
Console.log (P.lastindex);//0
Console.log (p.exec (s));//[' a ']
console.log (p.lastindex);//1
Console.log (P.exec (s));//[' B ']
console.log (p.lastindex);//2 console.log
(p.exec (s));//null
Console.log (p.lastindex);//0
var p =/\w/g;
var s1 = ' ab ';
var s2 = ' ba ';
Console.log (P.lastindex);//0
Console.log (p.exec (S1));//[' a ']
console.log (p.lastindex);//1
Console.log (p.exec (S2));//[' a ']
console.log (p.lastindex);//2

Constructor properties

RegExp constructor properties are considered static properties that vary based on the most recent regular expression operation performed

There are two ways to access them, that is, long property names and short property names. Short attribute names are mostly not valid ECMAScript identifiers, so they must be accessed through the square brackets syntax

Long property name    short attribute name   description
input       $_ The        most recent string to match
lastmatch     $&        last match
Lastparen     $+        last matched capturing group
leftcontext    $ '        input string lastmatch before text
multiline     $*        A Boolean value that indicates whether all expressions use        the text after lastmarch in the rightcontext $ ' input string in multiple-line mode    

Using these properties, you can extract more specific information from the actions performed by the Exec () method or the test () method

Test () tests whether a string matches a regular expression and returns a Boolean value of
var text = ' This has been a short summer ';
var pattern =/(.) hort/g;
if (pattern.test (text)) {
  console.log (regexp.input);//' This has been a short summer '
  console.log ( Regexp.leftcontext);/' This has been a '
  console.log (regexp.rightcontext);//' Summer '
  console.log ( Regexp.lastmatch);//' Short '
  console.log (Regexp.lastparen);//' s '
  console.log (regexp.multiline);//false
  console.log (regexp[' $_ ']);/' This has been a short summer '
  console.log (regexp[' $ ']);/' This has been a ' C12/>console.log (regexp["$"]);//' Summer '
  console.log (regexp[' $& ']);//' Short '
  console.log (RegExp ['$+']);/ /' s '
  console.log (regexp[' $* ');//false    
}

JavaScript has 9 constructor properties for storing capturing groups, which are automatically populated when the exec () or test () method is invoked

[note] theoretically, the regexp.$0 that should hold the entire expression matching text does not exist, and the value is undefined

Regexp.$1\regexp.$2\regexp.$3 ... To regexp.$9 to store first, second ... Nineth matching capturing group
var text = ' This has been a short summer ';
var pattern =/(..) or (.) /g;
if (pattern.test (text)) {
  console.log (regexp.$1);//sh
  Console.log (regexp.$2);//t
}

Instance method

A total of 5 instances of RegExp objects are divided into two categories. including ToString (), tolocalstring (), valueof (), the general method of 3 objects and test (), exec () regular matching method

Object General Methods

The RegExp object inherits the three methods of the Universal Method ToString (), tolocalestring (), valueof () of the Object object

"ToString ()"

The ToString () method returns the literal amount of the regular expression

"toLocaleString ()"

The toLocaleString () method returns the literal amount of the regular expression

"ValueOf ()"

The valueof () method returns the return of the regular expression object itself

[note] Regardless of how the regular expression is created, all three methods return only their literal form

var pattern = new RegExp (' [Bc]at ', ' gi ');
Console.log (Pattern.tostring ()); '/[bc]at/gi '
console.log (pattern.tolocalestring ());//'/[bc]at/gi '
console.log (pattern.valueof ()); [Bc]at/gi

var pattern =/[bc]at/gi;
Console.log (Pattern.tostring ()); '/[bc]at/gi '
console.log (pattern.tolocalestring ());//' [Bc]at/gi '
Console.log (pattern.valueof ());///[ Bc]at/gi

Regular Matching method

Regular-expression RegExp objects have only two regular matching methods: Exec () and test () respectively

"Exec ()"

The exec () method is designed specifically for capturing groups, accepting a parameter that is the string to which the pattern applies. It then returns an array containing the matching information and returns null without a match

In the array of matches, the first item is a string that matches the entire pattern, and the other is a string that matches the capturing group in the pattern, and if there is no capturing group in the pattern, the array contains only one item

The returned array contains two additional attributes: Index and input. Index indicates the position of the match in the string, and input represents the string that applies the regular expression

var text = ' Mom and Dad and baby and others ';
var pattern =/mom (and dad (and baby)?)? /gi;
var matches = pattern.exec (text);
Console.log (pattern,matches);
Pattern.lastindex:20
//matches[0]: ' Mom and Dad and Baby '
//matches[1: ' and dad and Baby '
//matches[2]: ' and baby '
//matches.index:0
//matches.input: ' Mom and Dad and baby and others '

For the Exec () method, it returns only one match at a time, even if the global flag (g) is set in the pattern. Calling exec () multiple times on the same string without setting the global flag always returns the information for the first occurrence, and in the case of setting the global flag, each call EXEC () continues to find a new match in the string

var text = ' Cat,bat,sat,fat ';
var pattern1 =/.at/;
var matches = pattern1.exec (text);
Console.log (pattern1,matches);
pattern1.lastindex:0
//matches[0]: ' Cat '
//matches.index:0
//matches.input: ' Cat,bat,sat,fat '

var text = ' Cat,bat,sat,fat ';
matches = pattern1.exec (text);  
Console.log (pattern1,matches);  
pattern1.lastindex:0
//matches[0]: ' Cat '
//matches.index:0
//matches.input: ' Cat,bat,sat,fat '
var text = ' Cat,bat,sat,fat ';
var pattern2 =/.at/g;
var matches = pattern2.exec (text);
Console.log (pattern2,matches);  
Pattern2.lastindex:3
//matches[0]: ' Cat '
//matches.index:0
//matches.input: ' Cat,bat,sat,fat '

var text = ' Cat,bat,sat,fat ';
matches = pattern2.exec (text);
Console.log (pattern2,matches);  
Pattern2.lastindex:7
//matches[0]: ' Bat '
//matches.index:4
//matches.input: ' Cat,bat,sat,fat '

"Tips" Use the Exec () method to find all the locations and all the values that match

var string = ' j1h342jg24g234j 3g24j1 ';
var pattern =/\d/g;
var ValueArray = [];//value
var indexarray = [];//location
var temp;
while ((Temp=pattern.exec (string))!= null) {
  Valuearray.push (temp[0]);
  Indexarray.push (Temp.index); 
}
["1", "3", "4", "2", "2", "4", "2", "3", "4", "3", "2", "4", "1" [1, 3, 4, 5, 8, 9, all,]
co Nsole.log (Valuearray,indexarray);

"Test ()"

The test () method tests whether a regular expression can find a matching literal in a string, receives a string parameter, returns True when it matches, or returns false

var text = ' 000-00-000 ';
var pattern =/\d{3}-\d{2}-\d{4}/;
if (pattern.test (text)) {
  Console.log (' The pattern is matched ');
}

Similarly, when the test () method is invoked, it causes a change in the Lastindex property of the RegExp object. If global mode is specified, every time the test () method is executed, an attempt is made to match from the lastindex offset value in the string, so the different strings are validated multiple times with the same regexp, and the lastindex value must be set to 0 after each call

var pattern =/^\d{4}-\d{2}-\d{2}$/g;
Console.log (pattern.test (' 2016-06-23 '));//true
Console.log (pattern.test (' 2016-06-23 '));//false

// The correct way to do this is to reset the lastindex to 0
var (=/^\d{4}-\d{2}-\d{2}$/g) before validating the different strings;
Console.log (pattern.test (' 2016-06-23 '));//true
pattern.lastindex = 0;
Console.log (pattern.test (' 2016-06-23 '));//true

As described earlier, JavaScript has 9 constructor properties for storing capturing groups that are automatically populated when the exec () or test () method is invoked

[note] Theoretically, the regexp.$0 that should hold the entire expression matching text does not exist, and the value is undefined

if (/^ (\d{4})-(\d{2})-(\d{2}) $/.test (' 2016-06-23 ')) {
  console.log (regexp.$1);//' 2016 ' Console.log
  (RegExp $);//' Console.log '
  (regexp.$3);//' Console.log '
  (regexp.$0);//undefined
}

The above is a small series for you to bring the JavaScript type system _ Regular expression regexp type of all content, I hope we support cloud Habitat Community ~

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.