JS regular expressions get the method of grouping content

  • 2020-03-29 23:45:38
  • OfStack

var testStr = "now test001 test002";   
var re = /test(d+)/ig;    
var r = "";   
while(r = re.exec(testStr)) {   
    alert(r[0] + "  " + r[1]);   

You can also use teststr.match (re), but then you can't have the option of g and only get the first match.

Another note:

Properties and methods of regular expression objects:
Predefined regular expressions have the following static properties: input, multiline, lastMatch, lastParen, leftContext,

RightContext and $1 through $9. Where input and multiline can be preset. The values of the other attributes are based on the exec or test methods that have been executed

Different conditions are assigned different values. Many properties have both long and short (perl-style) names, and both names point to the same value. (JavaScript emulates perl's regular expressions)

Properties of the regular expression object:
Attribute meaning
The $1... $9 is the matched substring & PI if it exists;
The $_ see input 
$* see multiline 
$& see lastMatch 
$+ see lastParen 
$` see leftContext 
$' see rightContext 
Constructor  Creates a special function prototype of an object  
Global  Matches (bool type)  throughout the string;
IgnoreCase matches whether or not to ignoreCase (bool type) 
Input string   matched;
LastIndex  Last matched index  
LastParen  The last substring in parentheses  
LeftContext  Last match to the left substring  
Multiline  Whether to perform multi-line matching (bool type) 
Prototype  Allows additional attributes to be given to an object  
RightContext most recently matches the right substring  
Source  Regular expression pattern  
LastIndex  The index of the last match

Method of regular expression object:
Methods the meaning
Compile  This should mean redefining the contents of the regular expression
Exec performs lookups, which can be done multiple times using a while approach
Test matches  
ToSource returns the definition of a specific object (literal execution), whose value can be used to create a new object. Overloading the object.tosource method.  
ToString returns a string for a particular object. Overloading the object.tostring method.  
ValueOf  Returns the original value of a particular object. This is obtained by overloading the object.valueof method


<script language="JavaScript"> 
var myReg = /(w+)s(w+)/; 
var str  = "John Smith"; 
var newstr = str.replace(myReg, "$2, $1"); 

Will print "Smith, John"

Related articles: