Named capturing groupings in JS regular

Source: Internet
Author: User

Suppose you see such a function in a strange code:

function tolocaldate (date) {  return date.replace (/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")}

Just look at this function can you tell if it wants to replace "day-month-year" with "month-day-year" or vice versa? Anonymous capture grouping It's not possible to do this, so the named capture group is on the pitch:

function tolocaldate (date) {  return date.replace (/(? <month>\d{2})-(? <day>\d{2})-(?< YEAR>\D{4})/, "$<day>-$<month>-$<year>")}

As the saying goes, "a good variable name race over a line of comments", the name of the capture group is a big role is that it can play the role of annotations.

Also, the advantage of naming capturing groupings is that if you are modifying a regular to introduce a new grouping on the left side of the existing grouping, you also have to remember to update the number of the existing inverse reference. For example, to change (foo) \1 to (bar) (foo) \1, then you have to change the original \1 to the \2,replace () method in the second parameter of the same change.

Grammar

The syntax for naming the capture group itself is (? <name> ...), which is more than the normal grouping of a?<name> typeface, where the starting method of name is the same as the variable name you normally use (but here the keyword is also available).

The syntax for referencing a named grouping is \k<name>, and note that named groupings can also be reversed by a numeric index, such as:

// true

The reverse reference in the Replace string of the replace () method is used $<name>:

// "A-BC", same as $ still available

In summary, there are three syntax related to named groupings, namely?<name>, \k<name>, $<name>, and the same points are wrapped with angle brackets around the group name.

Usage in the API is used in exec () and match ():
// {month: ",", Day: " +", Year: "}"  = Groups

The exec () and match () method returns an array of groups attributes that contain the names of each named group and the values they match, and the ES6 syntax makes it easy to extract the desired fields. Note that this groups property exists only if there is at least one named group in the current regular, such as:

// undefined, because there are no named groupings
Use in replace (/.../, replacement):

Replacement is an example of a string, which is mainly described here as the case of a function:

"04-25-2017". Replace (/(? <month>\d{2})-(? <day>\d{2})-(? <year>\d{4})/, (.... args) = {  = Args.slice ( -1) [0]  = groups  return ' ${day}-${month}-// "25-04-2017"

In other words, at the very end of the argument list, a groups object is passed. Similarly, if there is no named grouping in the regular, this parameter does not exist.

Abnormal conditions

The grouping name cannot have duplicates:

// syntaxerror:duplicate Capture Group name

To reverse reference a nonexistent group name:

// syntaxerror:invalid named capture referenced //True, for backwards compatibility under non-Unicode, the \ in front of K is discarded

A nonexistent grouping is referenced in the replacement string of the Reaplce () method:

// Syntaxerror:invalid Replacement String // "$<bar>", backward compatible when not containing named groupings
Summarize

V8 has now fully implemented the proposed https://tc39.github.io/proposal-regexp-named-groups/for named capture groupings.

Named groupings have some benefits, but I personally feel that the longer it is, the more difficult it is to read, especially the added length is a bunch of parentheses and angle brackets. In terms of readability, named groupings may be counterproductive, especially for regular bitter hands.

Named capturing groupings in JS regular

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.