JavaScript regular expression grouping and matching _ javascript skills

Source: Internet
Author: User
How can I write a regular expression to match both numbers? A simple character expression cannot be completed. in this case, we can define a character set combination (character class) for matching. This is the group match. Syntax

Metacharacters (pattern): used for group matching repeatedly

Attribute $1 ~ $9 if it exists, it is used to obtain the matched substring in the corresponding group.

\ 1 or $1 is used to match the content in the first group.

\ 2 or $2 is used to match the content in the first group.

...

\ 9 or $9 is used to match the content in the first group.

Usage example

Var reg =/(A +) (B | C | D) +) (E +)/gi; // This regular expression has four groups // ing relations // RegExp. $1 <-> (A +) // RegExp. $2 <-> (B | C | D) +) // RegExp. $3 <-> (B | C | D) // RegExp. $4 <-> (E +)

The above code also provides $1 ~ $9 usage

$1 ~ $9 is a pre-defined static attribute of a regular expression, which is referenced by RegExp. $1.

Group nesting relationship description

The code above can also describe the nesting relationship of groups.

// Test environment: Chrome browser var str = "ABCDE"; var reg =/(A +) (B | C | D) +) (E +)/gi; str. match (reg); // output: ["ABCDE" reg.exe c (str, 'I'); // output: ["ABCDE", "A", "BCD ", "D", "E"] RegExp. $1; // output: "A" RegExp. $2; // output: "BCD" RegExp. $3; // output: "D" RegExp. $4; // output: "E"

In this way, we can clearly see the nested relationship of the group.

To sum up, when a large group contains a small group, a small group is the group that is placed after the large group, and so on.

The above is all the content of this article. I hope you will like it.

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.