JS regular function match, exec, test, search, replace, split use the introduction set

Source: Internet
Author: User
Tags first string

The original Http://www.jb51.net/article/28007.htm JS regular function match, exec, test, search, replace, split use the introduction set, learning regular expression of friends can refer to. Match Method
Use the regular expression pattern to perform a lookup on a string and return the result that contains the lookup as an array. Stringobj.match (rgexp) parameter
Stringobj required option. A string object or string literal on which to find. Rgexp
Required option. is a 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 the match expression matches the global tag G, all occurrences will appear without loops, but all matches will not contain sub-matches. Example 1:
function Matchdemo () {var r, re;//declare 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 all four occurrences of "Ain", R[0], r[1], r[2], r[3]. But no child matches 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 looked up; index: the position (bit) where the match results are located;
Lastinput: The position of the next matching result;
Arr: result value, Arr[0] Full match result, arr[1,2 ...] is a sub-match of () within an expression, from left to right .... Example 2:Copy CodeThe code is as follows: function regexptest () {var src= "Http://sumsung753.blog.163.com/blog/I Love you!"; var re =/\w+/g; Note that G will match 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 loop once causes the RE to look for the next match in the G function. 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: 0-1:i//0 for index,i position, 1 for next match location 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
Note: According to the manual, EXEC returns only the first value of the matching result, such as the previous example if you do not use a while loop, will only return ' I ' (although the I space after love and you both conform to the expression), regardless of the RE expression with no global tag G. However, if a global tag is set for the regular expression g,exec the lookup begins at the position indicated by the value of LastIndex. If the global flag is not set, Exec ignores the value of LastIndex and starts the search from the beginning of the string. With this feature you can repeatedly call exec to traverse all matches, equivalent to match with the G flag.
Of course, if the regular expression forgets to use the G, but also uses the loop (for example: while, for and so on), the exec will loop each time first, causes the dead loop. The output of Exec will contain sub-matches.
Example 3:Copy CodeThe code is as follows: function Execdemo () {var r, re;//declare 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
The 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 looked up. Rgexp.test (str) parameter rgexp
Required option. A regular expression object that contains a regular expression pattern or an available flag. STR required option. The string on which to test the lookup. The description test method checks whether the string matches the given regular expression pattern, returns true if it is, or returns false. Example 4:Copy CodeThe code is as follows: function Testdemo (Re, s) {var S1;
if (Re.test (s)) S1 = "Match regular"; else S1 = "does not match the regular formula";
Return ("'" + S + "'" + S1 + "'" + Re.source + "'");} Window.onload = document.write (Testdemo (/ab/, ' cdef ')); Output: ' Cdef ' does not match regular type ' AB '
Note: Test () inherits the Lastindex property of the regular expression, which should be noted when matching the global flag G. Example 5:Copy CodeThe code is as follows: function Testdemo () {var r, re;//declare 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 Result: true false true
When the second call to test (), lastindex points to the next match location 1, so the second match is not successful, lastindex again points to 0, is equal to the third and re-match. The following example shows the Lastindex property of test:
Example 6:Copy CodeThe code is as follows: function Testdemo () {var r, re;//declare 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: Each time the LastIndex property of test () is re-directed to 0,re.lastindex = 0;
Search method
Returns the position (partial shift) of the first substring that matches the regular expression find content. Stringobj.search (rgexp) parameter
Stringobj required option. The string object or string literal on which to look. Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags. Note: If found, returns the offset bit at the beginning of the Fu Zhi, otherwise returns-1. Example 6:Copy CodeThe code is as follows: function Searchdemo () {var r, re;//declare 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); Finds a 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 the string after the literal substitution based on the regular expression. Stringobj.replace (Rgexp, replacetext) parameters
Stringobj required option. A string object or string literal to perform the substitution. The string is not modified by the Replace method. Rgexp
Required option. is a regular expression object that contains a regular expression pattern or an available flag. It can also be a String object or literal. If Rgexp is not a regular expression object, it will be converted to a string, and the exact lookup is done, and 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 by the object. In Jscript 5.5 or later, the ReplaceText parameter can also be a function that returns alternate text. Indicates that the result of the Replace method is a copy of the Stringobj object that completed the specified substitution. means that the matching item is specified for substitution, and the other remains unchanged as the stringobj return. ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function instead of 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 parameter 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. Functions can be used for more complex operations. Example 7:Copy CodeThe code is as follows: function f2c (s) {var test =/(\d+ (\.\d*)?) f\b/g; Description Fahrenheit temperature may be: 123F or 123.4F. Note that the G-mode return is used here (s.replace
(Test, function (regstr,$1,$2,$3,newstrobj) {return ("<br/>" + regstr + "<br/>" + ($1-32) *) + "C" + "<br /> "+//The following two lines to replace the $ +" <br/> "+ $ +" <br/> "+ newstrobj +" <br/> "); } )
); } document.write (F2C ("water:32.2f and oil:20.30f."); Output: Water://does not match the regular character, output 32.2F//The original string of the first string that matches the regular, regstr 0.10000000000000142C//matches the first substring of the first string matched with the regular match the substitution result $ 1.2//The substitution result of the second sub-pattern match of the first string that matches the regular, here we do not replace it with the first sub-match of the first string that matches the number $7//and the regular match occurs at an offset of $ water:32.2f and oil:20.30f. Original string newstrobj and oil://characters that do not match the regular
20.30F//Match the original string of the second string with the regular -5.85c//match the first sub-pattern of the second string with the regular match the replacement result
.30//The substitution result of the second sub-pattern match of the second string that matches the regular match, where we do not replace it with the first sub-match of the second string that matches the regular match, the offset water:32.2f and oil:20.30f. The original string. The function parameters above the characters that do not match the regular are all used. In practice, we only need to replace XXF with XXC, and on request we do not need to write so many parameters. Example 8:Copy CodeThe code is as follows: function f2c (s) {var test =/(\d+ (\.\d*)?) f\b/g; Description Fahrenheit temperature Possible mode: 123F or 123.4F return (s.replace (test,
function (strobj,$1) {return (($1-32) + "C");}) );
} document.write (F2C ("water:32.2f and oil:20.30f."); Output: water:0.10000000000000142c and oil: -5.85c. More applications:
Example 9:Copy CodeThe code is 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
The Split method splits a string into substrings and returns the result as an array of strings. Stringobj.split ([separator[, limit]]) parameter stringobj required option. The String object or text to be decomposed. 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 when separating the string. If this option is omitted, a single element array containing the entire string is returned. Limit
Options are available. This value is used to limit the number of elements in the returned array. Demonstrates that the result of the split method is an array of strings, which is decomposed for each occurrence of separator in stingobj. Separator is not returned as part of any array element. Example 10:Copy CodeThe code is as follows: function Splitdemo () {var s, SS;
var s = "The rain in Spain falls mainly in the plain."; Regular expressions, separated by a large non-writable s. SS = S.split (/s/i); return (SS); }
document.write (Splitdemo ()); Output: The rain in, pain fall, mainly in the plain.
the Exec () method of the JS regular expression, the match () method, and the search () method

Look at the code first:

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 popup boxes are as follows:

The results are analyzed as follows:

1, regexp the Exec () method, has a string parameter, returns an array, the first entry of the array is the first match, the other is a 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 all the matching data contained in the string. This method invokes a string object and passes it a RegExp object. So the second pop-up statement returns all arrays that conform to 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 matched value. So the third place that pops up is "1", that is, the second character matches. 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.