JS regular function match, exec, test, search, replace, split use introduction set _ Regular expression

Source: Internet
Author: User
Tags first string
Match Method
Performs a lookup on a string using the regular expression pattern and returns the result that contains the lookup as an array.
Stringobj.match (RGEXP)
Parameters
Stringobj
Required option. A string object or string literal to find it.
Rgexp
Required option. Is the regular expression object that contains the regular expression pattern and the available flags. It can also be a variable name or string literal that contains the regular expression pattern and the available flags.
The rest of the instructions are the same as exec, except that if match's expression matches the global tag G, all occurrences will appear without looping, but all matches will not contain child matches.
Example 1:
function Matchdemo () {var r, re;//declaring variable. var s = "The rain in Spain falls mainly in the plain"; Re =/(a) in/ig; Creates a regular expression pattern. r = S.match (re); Try to match the search string. document.write (R); The returned array contains four matches for all "ain" occurrences, r[0], r[1], r[2, r[3]. But there is no child match a. Output Result: Ain,ain,ain,ain
exec method
Finds in a string with a regular expression pattern, returns the first value (array) of the lookup result, and returns null if the match fails.
Rgexp.exec (str)
Parameters
Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags.
Str
Required option. The string object or string literal in which to perform the lookup.
The returned array contains:
Input: The value of the entire string being searched;
Index: the location (bit) where the result is matched;
Lastinput: The position of the next match result;
Arr: result value, Arr[0] Full match result, arr[1,2 ...] Matches the child of the expression inside (), from left to right for 1,2 ....
Example 2:
Copy Code code as follows:

function Regexptest () {
var src= "Http://sumsung753.blog.163.com/blog/I Love you!";
var re =/\w+/g; Note that G matches the full text, and will never return only the first match.
var arr;
while ((arr = re.exec (src))!=null) {//exec causes Arr to return the first match, while the second loop once will make the re look for the next match in G action.
document.write (Arr.index + "-" + Arr.lastindex + ":" + arr + "<br/>");
For (key in arr) {
document.write (key + "=>" + Arr[key] + "<br/>");
}
document.write ("<br/>");
}
}
Window.onload = Regexptest ();

Output results:
0-1:i//0 for Index,i location, 1 for next match
Input=>i Love you!
Index=>0
Lastindex=>1
0=>i
2-6:love
Input=>i Love you!
Index=>2
Lastindex=>6
0=>love
7-10:you
Input=>i Love you!
Index=>7
Lastindex=>10
0=>you
Description: According to the manual, EXEC returns only the first value of the matching result, such as the previous example, if a while loop is not used, will only return ' I ' (although love after the I space and you all conform to the expression), regardless of the RE expression with the use of global tag G. However, if you set the global tag for a regular expression g,exec start the lookup from the location indicated by the value lastindex. If the global flag is not set, EXEC ignores the lastindex value and starts the search from the beginning of the string. Using this feature, you can repeatedly call exec to iterate through all the matches, equivalent to match with the G flag.
Of course, if the regular expression forgets to use G, and then uses the loop (for example: while, for, etc.), Exec loops the first one each time, causing a dead loop.
EXEC's output will contain child matches.
Example 3:
Copy Code code as follows:

function Execdemo () {
var r, re; Declare a variable.
var s = "The rain in Spain falls mainly in the plain";
Re =/[\w]* (AI) n/ig;
R = re.exec (s);
document.write (R + "<br/>");
For (key in R) {
document.write (key + "-" + R[key] + "<br/>");
}
}
Window.onload = Execdemo ();

Output:
Rain,ai
Input-the rain in Spain falls mainly in the plain
Index-4
LastIndex-8
0-rain
1-ai
Test method
Returns a Boolean value that indicates whether the given regular expression is matched in the string being searched.
Rgexp.test (str)
Parameters
Rgexp
Required option. A regular expression object that contains the regular expression pattern or the available flags.
Str
Required option. The string on which to test the lookup.
Description
The test method checks whether the string matches the given regular expression pattern, returns true if it is, or returns false.
Example 4:
Copy Code code as follows:

function Testdemo (Re, s) {
var S1;
if (Re.test (s))
S1 = "Matching regular formula";
Else
S1 = "mismatched regular formula";
Return ("" "+ S +" "" + S1 + "'" + Re.source + "");
}
Window.onload = document.write (Testdemo (/ab/, ' cdef '));

Output result: ' Cdef ' does not match regular type ' AB '
Note: Test () inherits the Lastindex property of the regular expression, which should be noted when matching global flag G.
Example 5:
Copy Code code as follows:

function Testdemo () {
var r, re; Declare a variable.
var s = "I";
re =/i/ig; Creates a regular expression pattern.
document.write (Re.test (s) + "<br/>"); Returns a Boolean result.
document.write (Re.test (s) + "<br/>");
document.write (Re.test (s));
}
Testdemo ();

Output results:
True
False
True
When you call Test () the second time, lastindex points to the next match at location 1, so the second match is unsuccessful, lastindex points back to 0, and then the third time it is matched again. The following example shows the Lastindex property of test:
Example 6:
Copy Code code as follows:

function Testdemo () {
var r, re; Declare a variable.
var s = "I";
re =/i/ig; Creates a regular expression pattern.
document.write (Re.test (s) + "<br/>"); Returns a Boolean result.
document.write (Re.lastindex); Returns a Boolean result.
}
Testdemo ();

Output:
True
1
Workaround: The Lastindex property of test () is again pointed to 0,re.lastindex = 0 each time;

Search method
Returns the position (offset) of the first substring that matches the lookup content of the regular expression.
Stringobj.search (RGEXP)
Parameters
Stringobj
Required option. The string object or string literal to find on.
Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags.
Note: Returns the offset bit at the beginning of the Fu Zhi if found, or 1.
Example 6:
Copy Code code as follows:

function Searchdemo () {
var r, re; Declare a variable.
var s = "The rain in Spain falls mainly in the plain.";
re =/falls/i; Creates a regular expression pattern.
Re2 =/tom/i;
r = S.search (re); Find the string.
r2 = S.search (Re2);
Return ("R:" + R + "; R2:" + R2); Returns a Boolean result.
}
document.write (Searchdemo ());

Output: r:18;r2:-1
Replace method
Returns the copy of a string that is replaced with text based on a regular expression.
Stringobj.replace (Rgexp, ReplaceText)
Parameters
Stringobj
Required option. The string object or string literal to perform the substitution. The string is not modified by the Replace method.
Rgexp
Required option. Is the regular expression object that contains the regular expression pattern or the available flags. It can also be a String object or text. If Rgexp is not a regular expression object, it is converted to a string and the exact lookup is made; do not attempt to convert the string to a regular expression.
ReplaceText
Required option. is a string object or string literal, and the position in each matching rgexp in Stringobj is replaced with the text contained in that object. In the Jscript 5.5 or later version, the ReplaceText parameter can also be a function that returns the replacement text.
Description
The result of the Replace method is a copy of the Stringobj object that completes the specified replacement. The meaning is specified as a replacement for the matching item, and the other invariant is returned as stringobj.
ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function rather than a string. In this case, each match calls the function, and the string it returns is used as the replacement text. The first parameter of the function is a string that matches the pattern. The next argument is a string that matches the subexpression in the pattern, and can have 0 or more of these parameters. The next argument is an integer that declares where the match appears in the Stringobject. The last parameter is the stringobject itself. The result is a string value that replaces each matched substring with the corresponding return value of the function call. function as a parameter can be more complex operations.
Example 7:
Copy Code code as follows:

function f2c (s) {
var test =/(\d+ (\.\d*)?) f\b/g; The possible modes of Fahrenheit temperature are: 123F or 123.4F. Note that G mode is used here.
Return (S.replace
(Test,
function (regstr,$1,$2,$3,newstrobj) {
Return ("<br/>" + regstr + "<br/>" + ($1-32) * 1/2) + "C" + "<br/>" +//The following two lines to replace
$ + "<br/>" + $ + "<br/>" + newstrobj + "<br/>");
}
)
);
}
document.write (F2C ("water:32.2f and oil:20.30f."));

Output results:
Water://Does not match the regular character, output by the original character
32.2F//Regstr The original string of the first string that matches the regular match
0.10000000000000142C//Replaces the first child pattern of the first string with a regular match
.2//The replacement result of the second child pattern match for the first string that matches the regular match, where we have not replaced it with $
7//The offset of the first substring of the first string matching the regular match $
water:32.2f and oil:20.30f. Original String Newstrobj
and oil://not matching the regular characters
20.30F//The original string of the second string that matches the regular match
-5.85C//The first child pattern of the second string that matches the regular match and the matching result
.30//The replacement result of the second child pattern Match of the second string matching the regular match, where we have not replaced it
22//The offset of the first child of the second string that matches the regular match
water:32.2f and oil:20.30f. Original string
. Characters that do not match the regular
We've used all of the above function parameters. In practice, we only have to replace the XXF with the XXC, according to the requirements, we do not need to write so many parameters.
Example 8:
Copy Code code as follows:

function f2c (s) {
var test =/(\d+ (\.\d*)?) f\b/g; The possible modes of Fahrenheit temperature are: 123F or 123.4F
Return (S.replace
(Test,
function (strobj,$1) {
Return (($1-32) * 1/2) + "C");
}
)
);
}
document.write (F2C ("water:32.2f and oil:20.30f."));

Output: water:0.10000000000000142c and oil: -5.85c.
More applications:
Example 9:
Copy Code code as follows:

function f2c (s) {
var test =/([\d]{4})-([\d]{1,2})-([\d]{1,2})/;
Return (S.replace
(Test,
function ($0,$1,$2,$3) {
Return ($ + "/" + $);
}
)
);
}
document.write (f2c ("today:2011-03-29"));

Output: today:03/2011
Split method
Splits a string into a substring and returns the result as an array of strings.
Stringobj.split ([separator[, limit]])
Parameters
Stringobj
Required option. The String object or text to be exploded. The object is not modified by the split method.
Separator
Options available. A string or regular expression object that identifies whether one or more characters are used to delimit a string. If this option is omitted, an array of single elements containing the entire string is returned.
Limit
Options available. This value is used to limit the number of elements returned in an array.
Description
The result of the split method is an array of strings, where each occurrence of separator in the stingobj is decomposed. Separator is not returned as part of any array element.
Example 10:
Copy Code code as follows:

function Splitdemo () {
var s, SS;
var s = "The rain in Spain falls mainly in the plain.";
A regular expression, separated by an s that is not written in large.
SS = S.split (/s/i);
return (SS);
}
document.write (Splitdemo ());

Output: The rain in, pain fall, mainly in the plain.

The exec () method, Match () method and search () method of JS Regular expression

First look at the code:

var stomatch = "Test, Tes, TST, Tset, test, Tesyt, stes";
var reEs =/es/gi;
Alert (Rees.exec (Stomatch));
Alert (Stomatch.match (reEs));
Alert (Stomatch.search (reEs));

The contents of the three pop-up boxes are as follows:

The results were analyzed as follows:

1, RegExp exec () method, there is a string parameter, returns an array, the first entry of the array is the first match, and the other is the reverse reference. So the first returned result is the first matching value es (case-insensitive).

2. The string object has a match () method that returns a data containing all the matches in the string. This method invokes a string object and passes it a RegExp object. So the second pop-up statement returns all the arrays that match the regular expression.

3. The string method of search () is somewhat similar to indexof (), but it uses a RegExp object rather than just a substring. The search () method returns the position of the first matching value. So the third pop-up is "1", that is, the second character is matched. Note that the search () method does not support global matching of regular expressions (with parameter g).

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.