A correlation method for JavaScript regular expressions--regular expressions

Source: Internet
Author: User

The previous article introduced the basic syntax of JavaScript regular expressions to introduce the syntax of JavaScript regular expressions, with these basic knowledge, you can look at the regular expression in JavaScript application, before all begin, look at several properties of the RegExp instance

RegExp instance object has five properties

1.global: Global Search, default is False

2.ignoreCase: Case sensitive, default is False

3.multiline: Multiple-line search, default value is False

4.lastIndex: Is the next position of the last character in the first match of the current expression pattern, and the value of the Lastindex property changes each time the regular expression matches successfully.

5.source: text string for regular expression

In addition to compiling a regular expression into an internal format so that the compile () method is executed faster, the object has two common methods

Regobj.test (Strobj)

method is used to test whether a regular expression pattern is stored in a string parameter, and returns True if it exists, otherwise it returns false

Copy Code code as follows:

var reg=/\d+\.\d{1,2}$/g;reg.test (' 123.45 '); Truereg.test (' 0.2 '); Truereg.test (' a.34 '); Falsereg.test (' 34.5678 '); False

Regobj.exec (Strobj)

method is used for the regular expression pattern to run a lookup in a string, and if EXEC () finds a matching text, an array of results is returned. Otherwise, NULL is returned. In addition to the array elements and length properties, the Exec () method returns two properties. The Index property declares the position of the first character of the matching text. The input property holds a string that is retrieved.

When calling exec () of a Non-global RegExp object, the No. 0 element of the returned array is the text that matches the regular expression, and the 1th element is the text that matches the 1th subexpression of Regexpobject (if any), and the 2nd element is the 2nd of the RegExp object. The text (if any) that matches the subexpression, and so on.

When the exec () of a global RegExp object is invoked, it starts retrieving string string at the character specified by the Lastindex property of the RegExp instance. When exec () finds the text that matches the expression, after the match, it sets the Lastindex property of the RegExp instance to the next position in the last character of the text. You can iterate through all the matching text in a string by repeatedly calling the Exec () method. When exec () can no longer find the matching text, it returns null and resets the Lastindex property to 0.

Copy Code code as follows:

var reg=/\d/g;var r=reg.exec (' a1b2c3 '); Console.log (Reg.lastindex); 2r=reg.exec (' a1b2c3 '); Console.log (Reg.lastindex); 4

Two results of the execution of R

Copy Code code as follows:

var reg=/\d/g;while (r=reg.exec (' a1b2c3 ')) {Console.log (r.index+ ': ' +r[0]);}

You can see the result:

Copy Code code as follows:
1:13:25:3

In addition to the two methods above, some string functions can be passed into the RegExp object as arguments for some complex operations

Strobj.search (Regobj)

The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression. The search () method does not perform a global match, and it ignores flag g. It ignores the RegExp lastindex property at the same time and always retrieves it from the beginning of the string, which means it always returns the first matching position of Stringobject.

Copy Code code as follows:

' A1b2c3 '. Search (/\d/g); 1 ' a1b2c3 '. Search (/\d/); 1

Strobj.match (Regobj)

The match () method retrieves the string stringobject to find one or more text that matches the regexp. But whether the regexp has a significant effect on the result is the sign G.

If RegExp does not have a flag G, then the match () method can only perform a match in Strobj. If no matching text is found, match () returns NULL. Otherwise, it returns an array that holds information about the matching text it finds. The No. 0 element of the array holds the matching text, while the remaining elements hold the text that matches the subexpression of the regular expression. In addition to these regular array elements, the returned array also contains two object properties. The Index property declares the position of the starting character of the matching text in the Stringobject, and the input property declares a reference to the Stringobject.

Copy Code code as follows:

var r= ' aaa123456 '. Match (/\d/);

If the regexp has a flag G, the match () method performs a global search and finds all the matching substrings in the strobj. If no matching substring is found, NULL is returned. If one or more matching substrings are found, an array is returned. However, the contents of the array returned by the global match are very different from the former, and its array elements contain all the matching substrings in the strobj, and there is no index attribute or input property.

Copy Code code as follows:

var r= ' aaa123456 '. Match (/\d/g);

Strobj.replace (REGOBJ,REPLACESTR)

About the Replace method of the Strng object, we used to pass in two strings in the most common practice, but this approach has a flaw, only replace once

Copy Code code as follows:

' Abcabcabc '. replace (' BC ', ' X '); Axabcabc

The first parameter of the Replace method can also pass in the RegExp object, and passing in the regular expression can be more powerful and flexible when the Replace method is used

Copy Code code as follows:

' Abcabcabc '. Replace (/bc/g, ' X '); Axaxax ' ABCABCABC '. Replace (/bc/gi, ' X '); Axaxax

If the first parameter of the Replace method passes in a regular expression with a grouping, we can use $1...$9 in the second argument to get the corresponding grouping content, such as the <%x%> of the string 1<%2%>34<%567%>89 In exchange for $ #x #$, we can do this.

Copy Code code as follows:

' 1<%2%>34<%567%>89 '. Replace (/<% (\d+)%>/g, ' @#$1#@ ')//1@ #2 #@34@ #567 #@89

Of course there are many ways to do that, and here's just a demonstration. Using grouped content, we use @#$1#@ in the second parameter, which represents the grouped content being captured, which is often seen in some JS template functions to replace strings.

Strobj.replace (Regobj,function () {})

You can make replace more powerful by modifying the second argument of the Replace method, which in the previous introduction would only replace all matches with fixed content, but what if I wanted to wrap all the numbers in a string with parentheses?

Copy Code code as follows:

' 2398rufdjg9w45hgiuerhg83ghvif '. Replace (/\d+/g,function (r) {return ' (' +r+ ') ';}); "(2398) RUFDJG (9) W (HGIUERHG) ghvif"

The second parameter of the Replace method is passed into a function, which is called every time a match is replaced, a callback function of each substitution, and we use the first parameter of the callback function, which is the matching content, in fact, there are four parameters in the callback function.

1. The first parameter is very simple, is a matching string

2. The second parameter is the regular expression grouping content, without grouping there is no argument

3. The third parameter is the index of the match in the string

4. The fourth parameter is the original string

Copy Code code as follows:

' 2398rufdjg9w45hgiuerhg83ghvif '. Replace (/\d+/g,function (a,b,c) {Console.log (a + ' \ t ' +b+ ' \ t ' +c); return ' (' +a+ ') ';}); 2398 0 2398rufdjg9w45hgiuerhg83ghvif9 2398rufdjg9w45hgiuerhg83ghvif45 2398rufdjg9w45hgiuerhg83ghvif83 22 2398rufdjg9w45hgiuerhg83ghvif

This is not the case of grouping, printed out is the matching content, match index and the original string, see a grouped example, if we want to put a string of <%%> shell removed,<%1%><%2%><%3%> Into 123

Copy Code code as follows:
' <%1%><%2%><%3%> '. Replace (/<% ([^%>]+)%>/g,function (a,b,c,d) {Console.log (+ ' t ' +b+ ' \ T ' +c+ ' \ t ' +d); return b;}) 123<%1%> 1 0 <%1%><%2%><%3%> <%2%> 2 5 <%1%><%2%><%3%> <%3%> 3 Ten <%1%><%2%><%3%>

Replace with this parameter can achieve many powerful features, especially in complex string substitution statements that are frequently used.

Strobj.split (Regobj)

We often split strings into character arrays using the Split method

Copy Code code as follows:
' A,b,c,d '. Split (', '); ["A", "B", "C", "D"]

Similar to the Replace method, we can use regular expressions in some complex segmentation cases to solve

Copy Code code as follows:
' A1b2c3d '. Split (/\d/); ["A", "B", "C", "D"]

This way you can divide strings by numbers, and it's not very powerful. After reading these two blog basics can be used to the usual JavaScript regular expression of ease. Ask to capitalize the first letter of the English paragraph in a div in front of you, do you know what to do?

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.