The previous words
The basic syntax of regular expressions in javascript has been introduced earlier. The RegExp class of javascript represents regular expressions. Both String and RegExp define methods. Using regular expressions can perform powerful pattern matching, text retrieval and replacement. This article will introduce RegExp objects of regular expressions, and regular expressions involved
Attributes and methods
Object
Regular expressions in javascript are represented by RegExp objects, and there are two ways to write them: one is the literal method; the other is the constructor method
Perl writing method
Regular expression literal writing, also known as Perl writing, because the regular expression characteristics of JavaScript are borrowed from Perl
Regular expression literals are defined as characters contained between a pair of slashes (/) and 3 flags can be set
var expression = /pattern/flags;
The matching pattern of regular expressions supports the following 3 flags:
g: means global pattern, i.e. the pattern will be applied to all strings, rather than stopping immediately when the first match is found
i: Indicates case-insensitive mode, that is, the case of the pattern and string is ignored when determining the match.
m: represents multiline pattern, that is, when the end of a line of text is reached, it will continue to look for whether there is an item matching the pattern in the next line.
//Match all instances of 'at' of the string var p = /at/g;//test() method returns a boolean value to indicate whether the match can be found console.log(p.test('ata'));//trueconsole.log(p.test('aba'));//falseRegExp constructor
Like ordinary built-in objects, RegExp regular expression objects also support the form of new+RegExp() constructor.
The RegExp constructor receives two parameters: the string pattern to match and the optional flag string (flags). The three flags of the flag string and the literal have the same meaning: 'g', 'i', 'm'
Both parameters of the RegExp constructor are strings. And any expression defined using literal form can use constructors
//Match all instances of 'at' of the string var p1 = /at/g;//Same as above var p2 = new RegExp('at','g');[Note] The ECMAScript3 specification stipulates that a regular expression direct quantity will be converted into a RegExp object when executed to it. Each operation of the regular expression direct quantity represented by the same code returns the same object. The ECMAScript5 specification makes the opposite provisions, and the regular expression represented by the same code is directly counted each time.
All operations return new objects. IE6-8 has always been implemented in accordance with the ECMAScript5 specification, so there is no compatibility issue
Since the literals of regular expressions do not support variables, if variables appear in regular expressions, you can only use the RegExp constructor to splice the variables into the parameters of the RegExp constructor as string splicing.
【tips】Get element through 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 indicates whether the g flag ignoreCase: Boolean value indicates whether the i flag lastIndex: integer indicates the character position of the start searching for the next match. It counts from 0 multiline: Boolean value indicates whether the flag msource: string representation of the regular expression, which returns in the literal form rather than the string pattern passed in the constructor
var pattern = new RegExp('//[bc//]at','i');console.log(pattern.global);//falseconsole.log(pattern.ignoreCase);//true console.log(pattern.multiline);//falseconsole.log(pattern.lastIndex);//0console.log(pattern.source);//'/[bc/]at'If you use the exec() or test() function of RegExp and set the global pattern 'g', the matching of the regular expression will start from the lastIndex position, and the lastIndex will be reset after each under-match is successful. In this way, you can iterate repeatedly in the string and find each matching result in sequence. However, if you need to call the same RegExp exec() or test() method for different strings, this variable may also bring unexpected matching results. Therefore, when replacing the string, you should explicitly set the lastIndex of RegExp to 0
//exec() method returns the match in an array var p = //w/g;var s = 'ab';console.log(p.lastIndex);//0console.log(p.exec(s));//['a']console.log(p.lastIndex);//1console.log(p.exec(s));//['b']console.log(p.lastIndex);//2console.log(p.exec(s));//nullconsole.log(p.lastIndex);//0
var p = //w/g;var s1 = 'ab';var s2 = 'ba';console.log(p.lastIndex);//0console.log(p.exec(s1));//['a']console.log(p.lastIndex);//1console.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, namely long attribute names and short attribute names. Most short attribute names are not valid ECMAScript identifiers, so they must be accessed through square bracket syntax.
Long attribute name Short attribute name input $_ The last string to match lastMatch $& The last match lastParen $+ The last match last match capturing group leftContext $` input text before lastMatch multiline $* Boolean value indicating whether all expressions use multiline pattern rightContext $' The text after lastMarch in the Input string
Using these properties, more specific information can be extracted from operations performed by the exec() method or test() method
//test() is used to test whether a string matches a regular expression and returns a boolean value 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 ' console.log(RegExp['$'"]);//'s summer' console.log(RegExp['$&']);//'short' console.log(RegExp['$+']);//'s' console.log(RegExp['$*']);//false }JavaScript has 9 constructor properties for storing capture groups. These properties are automatically populated when calling exec() or test() methods.
[Note] Theoretically, the RegExp.$0 that should be saved to the entire expression matching text does not exist, the value is undefined
//RegExp.$1/RegExp.$2/RegExp.$3…to RegExp.$9 are used to store the first, second, ninth matching capture 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}Example method
There are 5 instance methods of RegExp objects, divided into two categories. Including three general methods of object: toString(), toLocalString(), valueOf(), and regular matching methods of test() and exec()
Object common method
RegExp object inherits three methods: toString(), toLocaleString(), and valueOf() of the Object object.
【toString()】
toString() method returns the literal of the regular expression
【toLocaleString()】
toLocaleString() method returns the literal of the regular expression
【valueOf()】
The valueOf() method returns the regular expression object itself
[Note] No matter what the regular expression is created, these three methods only return 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/givar pattern = /[bc]at/gi;console.log(pattern.toString()); // '/[bc]at/gi'console.log(pattern.toLocaleString()); // '[bc]at/gi'console.log(pattern.valueOf()); // /[bc]at/giRegular matching method
There are only two regular matching methods for RegExp objects: exec() and test() respectively.
【exec()】
The exec() method is designed specifically for capturing groups and accepts a parameter, namely the string to which the pattern is to be applied. Then return an array containing match information, and return null if there is no match.
In the match array, the first item is a string that matches the entire pattern, and the other items are a string that matches the capture group in the pattern. If there is no capture group in the pattern, the array only contains one
The returned array contains two additional properties: index and input. index means the match is at the position of the string, input means the string where the regular expression is applied
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, even if the global flag (g) is set in the pattern, it will return only one match at a time. Without setting the global flag, calling exec() multiple times on the same string will always return the information of the first match; while when setting the global flag, each call to exec() will continue to look for 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 exec() method to find all matching positions and all values
var string = 'j1h342jg24g234j 3g24j1';var pattern = //d/g;var valueArray = [];//value var indexArray = [];//position 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, 11, 12, 13, 16, 18, 19, 21]console.log(valueArray,indexArray);【test()】
The test() method is used to test whether the regular expression can find matching text in a string, receive a string parameter, and returns true when matching, otherwise returns false
var text = '000-00-000';var pattern = //d{3}-/d{2}-/d{4}/;if(pattern.test(text)){ console.log('The pattern was matched');}Similarly, when the test() method is called, the lastIndex property of the RegExp object will be changed. If a global pattern is specified, each time the test() method is executed, the lastIndex offset value in the string will be tried to match. Therefore, different strings are verified multiple times with the same RegExp. 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'));//trueconsole.log(pattern.test('2016-06-23'));//false//The correct way to do this is to reset lastIndex to 0var pattern = /^/d{4}-/d{2}-/d{2}$/g;console.log(pattern.test('2016-06-23'));//truepattern.lastIndex = 0;console.log(pattern.test('2016-06-23'));//truepattern.lastIndex = 0;console.log(pattern.test('2016-06-23'));//truepattern.lastIndex = 0;console.log(pattern.test('2016-06-23'));//trueAs mentioned earlier, JavaScript has 9 constructor properties for storing capture groups. These properties will be automatically filled when calling the exec() or test() method.
[Note] Theoretically, the RegExp.$0 that should be saved to the entire expression matching text does not exist, the value is undefined
if(/^(/d{4})-(/d{2})-(/d{2})$/.test('2016-06-23')){ console.log(RegExp.$1);//'2016' console.log(RegExp.$2);//'06' console.log(RegExp.$3);//'23' console.log(RegExp.$0);//undefined}The above is the javascript type system_regex RegExp type detailed explanation of the details. I hope everyone supports Wulin.com~