Grouping, alternation, and back reference

In the following table, you can find the patterns for grouping, alternation, and back reference. The grouping is used to group a set of characters in a Regex. The alternation is used to combine characters into a single regular expression, and the back reference is used to match the same text as previously matched by a capturing group:

Pattern

Description

Example

(x)

This groups characters together to create a clause, that is, it matches x and remembers the match. These are called capturing parentheses.

/(foo)/ matches and remembers "foo" in "foo bar".

()

Parenthesis also serves to capture the desired subpattern within a pattern.

/(dd)/(dd)/(dddd)/ matches "12", "12", and "2000" in "12/12/2000".

(?:x)

This matches x but does not capture it. In other words, no numbered references are created for the items within the parenthesis. These are called non-capturing parentheses.

/(?:foo)/ matches, but does not remember "foo" in "foo bar".

|

Alternation combines clauses into one regular expression, and then matches any of the individual clauses. x|y matches either x or y. It is similar to the "OR" statement.

/morning|night/ matches "morning" in "good morning" and matches "night" in "good night".

()

" " (where n is a number from 1-9) when added to the end of a regular expression pattern, allows you to back reference a subpattern within the pattern, so, the value of the subpattern is remembered and used as part of the matching.

/(no)1/ matches "nono" in "nono". "1" is replaced with the value of the first subpattern within the pattern, or (no), to form the final pattern.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset